package com.qianniu.napi.admin.service.akka;

import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.*;
import com.qianniu.napi.admin.mapper.*;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.thirdpart.print.Methods;
import com.qianniu.napi.common.util.*;
import jdk.nashorn.internal.runtime.regexp.joni.Regex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.*;

public class OrderActor extends UntypedActor {

    private final static Logger logger = LoggerFactory.getLogger(OrderActor.class);

    private MdpayMapper mdpayMapper = (MdpayMapper) SpringUtil.getBean("mdpayMapper");
    private IActgxService actgxService = (IActgxService) SpringUtil.getBean("actgxServiceImpl");
    private IUserService userService = (IUserService) SpringUtil.getBean("userServiceImpl");
    private ICouponService couponService = (ICouponService) SpringUtil.getBean("couponServiceImpl");
    private IUserstatService userstatService = (IUserstatService) SpringUtil.getBean("userstatServiceImpl");
    private IJifenService jifenService = (IJifenService) SpringUtil.getBean("jifenServiceImpl");
    private IFensService fensService = (IFensService) SpringUtil.getBean("fensServiceImpl");
    private IRedisService redisService = (IRedisService) SpringUtil.getBean("redisServiceImpl");
    private IFenxiaoService fenxiaoService = (IFenxiaoService) SpringUtil.getBean("fenxiaoServiceImpl");
    private IFenxiaoFanService fenxiaoFanService = (IFenxiaoFanService) SpringUtil.getBean("fenxiaoFanServiceImpl");
    private IOrderService orderService = (IOrderService) SpringUtil.getBean("orderServiceImpl");
    private ICzfanService czfanService = (ICzfanService) SpringUtil.getBean("czfanServiceImpl");
    private IJifenFlowService jifenFlowService = (IJifenFlowService) SpringUtil.getBean("jifenFlowServiceImpl");
    private IXnbiService xnbiService = (IXnbiService) SpringUtil.getBean("xnbiServiceImpl");
    private ICouponTplService couponTplService = (ICouponTplService) SpringUtil.getBean("couponTplServiceImpl");
    private IOrderGoodsService orderGoodsService = (IOrderGoodsService) SpringUtil.getBean("orderGoodsServiceImpl");
    private IGoodsService goodsService = (IGoodsService) SpringUtil.getBean("goodsServiceImpl");
    private IXnbiFlowService xnbiFlowService = (IXnbiFlowService) SpringUtil.getBean("xnbiFlowServiceImpl");
    private IAccountFlowService accountFlowService = (IAccountFlowService) SpringUtil.getBean("accountFlowServiceImpl");
    private IAccountService accountService = (IAccountService) SpringUtil.getBean("accountServiceImpl");
    private IMerchantAppService merchantAppService = (IMerchantAppService) SpringUtil.getBean("merchantAppServiceImpl");
    private IMaccountService maccountService = (IMaccountService) SpringUtil.getBean("maccountServiceImpl");
    private IMaccountFlowService maccountFlowService = (IMaccountFlowService) SpringUtil.getBean("maccountFlowServiceImpl");
    private IQnpay qnpay = (IQnpay) SpringUtil.getBean("qnpayImpl");
    private IPintuanOpenService pintuanOpenService = (IPintuanOpenService) SpringUtil.getBean("pintuanOpenServiceImpl");
    private IPintuanLogService pintuanLogService = (IPintuanLogService) SpringUtil.getBean("pintuanLogServiceImpl");
    private IMerchantConfigService merchantConfigServiceImpl = (IMerchantConfigService) SpringUtil.getBean("merchantConfigServiceImpl");
    private ITplformService tplformService = (ITplformService) SpringUtil.getBean("tplformServiceImpl");
    private ITemplatemsgService templatemsgService = (ITemplatemsgService) SpringUtil.getBean("templatemsgServiceImpl");
    private ISmslogService smslogService = (ISmslogService) SpringUtil.getBean("smslogServiceImpl");
    private IMconfigExtService mconfigExtService = (IMconfigExtService) SpringUtil.getBean("mconfigExtServiceImpl");
    private ICutpriceOpenService cutpriceOpenService = (ICutpriceOpenService) SpringUtil.getBean("cutpriceOpenServiceImpl");
    private IStoreService storeService = (IStoreService) SpringUtil.getBean("storeServiceImpl");
    private IShareOpenService shareOpenService = (IShareOpenService) SpringUtil.getBean("shareOpenServiceImpl");
    private IShareService shareService = (IShareService) SpringUtil.getBean("shareServiceImpl");
    private IGoodsQunzfService goodsQunzfService = (IGoodsQunzfService) SpringUtil.getBean("goodsQunzfServiceImpl");
    private StoreStatMapper storeStatMapper = (StoreStatMapper) SpringUtil.getBean("storeStatMapper");
    private LeagueMapper leagueMapper = (LeagueMapper) SpringUtil.getBean("leagueMapper");
    private SaccountMapper saccountMapper = (SaccountMapper) SpringUtil.getBean("saccountMapper");
    private LeagueMemberMapper leagueMemberMapper = (LeagueMemberMapper) SpringUtil.getBean("leagueMemberMapper");
    private ISaccountService saccountService = (ISaccountService) SpringUtil.getBean("saccountServiceImpl");
    private ISaccountFlowService saccountFlowService = (ISaccountFlowService) SpringUtil.getBean("saccountFlowServiceImpl");
    private IAddressService addressService = (IAddressService) SpringUtil.getBean("addressServiceImpl");

    @Override
    public void onReceive(Object message) {
        logger.info(">>>>>>OrderActor in");

        if (message instanceof String) {
            String msg = message.toString();
            logger.info(">>>>>>OrderActor receive message:" + msg);
            try {
                //格式 type+uid+toke
                String[] arr = msg.split("@");
                logger.info(">>>>>>receive arr.length=" + arr.length);
//             if (arr.length < 3) return;

                String type = arr[0];
                String yw1 = arr[1];
                String yw2 = arr.length >= 3 ? arr[2] : "";
                String yw3 = arr.length >= 4 ? arr[3] : "";
                String yw4 = arr.length >= 5 ? arr[4] : "";
                logger.info(">>>>>>receive type:" + type);
                logger.info(">>>>>>receive yw1:" + yw1);
                logger.info(">>>>>>receive yw2:" + yw2);

                switch (type) {
                    case Constants.AKKA_MSG_ORDER_CONFIRM:
                        logger.info(">>>>>>switch here[AKKA_MSG_ORDER_CONFIRM]");
                        payConfirm(yw1, yw2, yw3);
                        break;
                    case Constants.AKKA_MSG_RECHARGE_CONFIRM:
                        logger.info(">>>>>>switch here[AKKA_MSG_RECHARGE_CONFIRM]");
                        rechargeConfirm(yw1, yw2, yw3);
                        break;
                    case Constants.AKKA_MSG_FENXIAO_ORI:
                        logger.info(">>>>>>switch here[AKKA_MSG_FENXIAO_ORI]");
                        break;
                    case Constants.AKKA_MSG_FENXIAO_SCENE:
                        logger.info(">>>>>>switch here[AKKA_MSG_FENXIAO_SCENE]");
                        break;
                    case Constants.AKKA_MSG_HUIYUAN_SHENGJI:
                        logger.info(">>>>>>switch here[AKKA_MSG_HUIYUAN_SHENGJI]");
                        shengjiCheck(yw1, yw2, yw3);
                        break;
                    case Constants.AKKA_MSG_FAN_RUZHANG:
                        logger.info(">>>>>>switch here[AKKA_MSG_FAN_RUZHANG]");
                        fanliRuzhang(yw1, yw2);
                        break;
                    case Constants.AKKA_MSG_PAIDAN_RUZHANG:
                        logger.info(">>>>>>switch here[AKKA_MSG_PAIDAN_RUZHANG]");
                        paidanRuzhang(yw1, yw2);
                        break;
                    case Constants.AKKA_MSG_ORDER_NOTIFY:
                        logger.info(">>>>>>switch here[AKKA_MSG_ORDER_NOTIFY]");
//                        orderNotify(yw1, yw2);//oid,uid
                        break;
                    case Constants.AKKA_MSG_ORDER_DALIBAO:
                        logger.info(">>>>>>switch here[AKKA_MSG_ORDER_DALIBAO]");
                        orderDalibao(yw1, yw2, yw3);//oid,gid,uid
                        break;
                    case Constants.AKKA_MSG_ORDER_ZIGOUFAN:
                        logger.info(">>>>>>switch here[AKKA_MSG_ORDER_ZIGOUFAN]");
                        zigouFan(yw1, yw2);//oid,gid,uid
                        break;
                    case Constants.AKKA_MSG_ORDER_SHAREFAN:
                        logger.info(">>>>>>switch here[AKKA_MSG_ORDER_SHAREFAN]");
                        shareFanPay(yw1);//oid
                        break;
                    case Constants.AKKA_MSG_ORDER_QUNZHUANFA:
                        logger.info(">>>>>>switch here[AKKA_MSG_ORDER_QUNZHUANFA]");
                        qunzhuanfaPay(yw1);//群转发付佣金
                        break;
                    case Constants.AKKA_MSG_ORDER_STORE_PAY:
                        logger.info(">>>>>>switch here[AKKA_MSG_ORDER_STORE_PAY]");
                        orderStorePayRuzhang(yw1);//oid,fantime
                        break;
                    case Constants.AKKA_MSG_ORDER_MENGZHU_PAY:
                        logger.info(">>>>>>switch here[AKKA_MSG_ORDER_MENGZHU_PAY]");
                        orderMengzhuPayRuzhang(yw1);//oid,gid,uid
                        break;
                    case Constants.AKKA_MSG_ORDER_PLATFORM_PAY:
                        logger.info(">>>>>>switch here[AKKA_MSG_ORDER_PLATFORM_PAY]");
                        orderPlatformPayRuzhang(yw1);//oid,gid,uid
                        break;
                    case Constants.AKKA_QUAN_SHARE_PAY:
                        logger.info(">>>>>>switch here[AKKA_QUAN_SHARE_PAY]");
                        quanSharepay(yw1, yw2, yw3, yw4);//oid,gid,uid,fantime
                        break;
                    default:
                        break;
                }
            } catch (Exception e) {
                logger.error(">>>>>>OrderActor process error", e);
            }
        }
    }

//    //订单通知
//    private void orderNotify(String oid, String uid) {
//
//
//        Order order = orderService.selectById(oid);
//        if (order == null) {
//            return;
//        }
//
//        Long mpid = order.getMpid();
//        MerchantApp mapp = redisService.getMApp(mpid);
//        Long asmpid = mapp.getAsmpid();
//
//        if (asmpid != null) {
//            logger.debug("----------------------------------------------------------------------------orderNotify coming for mapp.getAsmpid()=" + mapp.getAsmpid());
//            //给商户端的用户发送通知
//            List<User> ulist = userService.selectList(new EntityWrapper<User>()
//                    .setSqlSelect("id,openid,phone")
//                    .eq("mpid", mapp.getAsmpid())
//                    .eq("asmpid", mapp.getId())
//            );
//            MerchantConfig mconfig = redisService.getMconfig(asmpid);
//            List<TemplateData> tpllist = new ArrayList<TemplateData>();
//
//            tpllist.add(new TemplateData("keyword1", order.getGoodsName()));
//            tpllist.add(new TemplateData("keyword2", DateUtil.toDateString(order.getCreatetime(), "yyyy-MM-dd hh:mm:ss")));
//            tpllist.add(new TemplateData("keyword3", order.getRealpay().toString() + "元"));
//            tpllist.add(new TemplateData("keyword4", order.getPhone()));
//            tpllist.add(new TemplateData("keyword5", order.getAddress()));
//
//            Templatemsg templatemsg = templatemsgService.selectOne(new EntityWrapper<Templatemsg>()
//                    .eq("tplcode", "payok")
//                    .eq("mpid", asmpid)
//                    .orderBy("id"));
//
//            for (User user : ulist) {
//                Tplform tplform = tplformService.selectOne(new EntityWrapper<Tplform>()
//                        .eq("state", 1)
//                        .eq("uid", user.getId())
//                        .orderBy("id"));
//                if (tplform == null) continue;
//
//                WxmappTemplate wxtpl = new WxmappTemplate();
//                wxtpl.setTouser(tplform.getOpenid());
//                wxtpl.setForm_id(tplform.getFormid());
//
//                wxtpl.setTemplate_id(templatemsg.getTplid());
//                String pageparam = mconfig.getShowForpay() == 1 ? "1" : "2";
//                wxtpl.setPage(templatemsg.getPage() + pageparam);
//                wxtpl.setTemplateDataList(tpllist);
//
//                ObjectUtil.sendTemplateMsg(redisService.getWxtoken(tplform.getMpid().toString()), wxtpl);//失效
//
//                tplform.setState(-1);
//                tplform.setModifytime(new Date());
//                tplform.updateById();
//                logger.debug("======orderNotify send tplmsg ok for user phone=" + user.getPhone());
//            }
//        }
//        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>orderNotify over");
//    }

    //首次支付成功通知
    public void payConfirm(String sn, String transaction_id, String paytime) {

        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>payConfirm");
        logger.info(">>>>>>payConfirm sn:" + sn);
        logger.info(">>>>>>payConfirm transaction_id:" + transaction_id);

        //===============1、更新订单状态【状态类】===============
        Order order = orderService.selectOne(new EntityWrapper<Order>().eq("order_no", sn));
        logger.info(">>>>>>payConfirm order:" + JSON.toJSONString(order));
        if (order == null) {
            logger.info(">>>>>>payConfirm order=null for sn=" + sn);
            return;
        }
        Long mid = order.getMid();
        Long mpid = order.getMpid();
        Long uid = order.getUid();
        Long sid = order.getSid();
        Long oid = order.getId();
        Store store = redisService.getStore(sid);
        MerchantConfig mconfig = merchantConfigServiceImpl
                .selectOne(new EntityWrapper<MerchantConfig>().eq("mpid", mpid));
        order.setStatus(order.getGtype() == 1 && (order.getShipperMethod() != null && order.getShipperMethod() < 4 && order.getShipperMethod() >= 1) ?
                StatusEnum.forsend.getVal() : StatusEnum.receving.getVal());
        if (order.getGtype() == 3 && order.getJduid() != null &&
                order.getShipperMethod() != null && order.getShipperMethod() == 1)
            order.setStatus(StatusEnum.forsend.getVal());

        if (order.getXftype().intValue() == XftypeEnum.maidan.getVal() ||
                order.getXftype().intValue() == XftypeEnum.smaidan.getVal() ||
                order.getType().intValue() == YXType.dalibao.getVal()) {
            //大礼包默认虚拟商品
            order.setStatus(StatusEnum.finish.getVal());
            order.setOkday(DateUtil.getToday());
        }

        OrderGoods og = new OrderGoods();
        og.setFhstate(3);
        og.setStatus(order.getStatus());
        og.setState(1);
        og.setModifytime(new Date());
        og.setPaytime(new Date());
        orderGoodsService.update(og, new EntityWrapper<OrderGoods>().eq("oid", oid));

        order.setTransactionId(transaction_id);
        order.setPaytime(DateUtil.toDate(paytime, "yyyyMMddhhmmss"));
        order.setModifytime(new Date());
        order.setModifier(0l);
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>payConfirm updateOrderStatus order=" + JSON.toJSONString(order));
        qnpay.updateOrderStatus(order, order.getStatus());
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>payConfirm updateOrderStatus over");

        //==============更新商家概况==============
        if (order.getSid() != null && order.getType().intValue() > 0 && order.getMinprice() != null) {
            StoreStat storeStat = storeStatMapper.selectById(order.getSid());
            if (storeStat == null) {
                storeStat = new StoreStat();
                storeStat.setStoreid(order.getSid());
            }
            storeStat.setTotal(storeStat.getTotal().add(order.getRealpay()));
            storeStat.setMshoukuan(storeStat.getMshoukuan().add(order.getMinprice()));
            storeStat.setRenqi(storeStat.getRenqi() + 5);
            storeStat.setOrders(storeStat.getOrders() + 1);
            storeStat.setUsers(orderService.getHdCanyushu(order.getSid()));

            storeStat.setModifytime(new Date());
            storeStat.setMpid(order.getUid());
            storeStat.updateById();
        }
        //==============更新商家概况END==============


        //=============2、更新账户+账户流水表【账户+状态类】=============
        //=============2.1、用户积分抵扣确认核销
        jifenService.jifenFlowConfirm(sn, uid);

        //=============2.1.2、插入商家会员=============
        //联盟版商家会员买单
        insertMchmembers(order);

        //=============2.2、用户券抵扣确认核销，需要先插入会员再更新券
        if (order.getCouponId() != null && order.getCouponId() > 0) {
            couponService.conponConfirm(sn, order.getCouponId(), uid);
        }

        //=============2.3、用户币抵扣确认核销一次只有一种
        xnbiService.xnbiFlowConfirm(sn, uid);

        //=============2.4、支付用户账户更新确认
        AccountFlow af = accountFlowService.selectOne(new EntityWrapper<AccountFlow>()
                .eq("sn", sn).eq("uid", uid).eq("iotype", IotypeEnum.output.getVal()));
        if (af != null) accountService.accountFlowConfirm(order, af, transaction_id);

        //=============2.5、用户交押金
        af = accountFlowService.selectOne(new EntityWrapper<AccountFlow>()
                .eq("sn", sn).eq("iotype", IotypeEnum.input.getVal()).eq("xftype", XftypeEnum.jyajin.getVal()));
        if (af != null) {
            logger.info("---------------------------------------------------payConfirm for shangjia shoukuanma shoukuan");
            accountService.accountFlowConfirm(order, af, transaction_id);
        }

        //=============2.6、实体店商家收款码收款（恰恰全积分支付）<特殊>
        af = accountFlowService.selectOne(new EntityWrapper<AccountFlow>()
                .eq("sn", sn).eq("iotype", IotypeEnum.input.getVal()).eq("xftype", XftypeEnum.mshoukuan.getVal()));
        if (af != null) {
            //即时入账不需核销（商家买单收款积分买单+优惠买单）
            accountService.accountFlowConfirm(order, af, transaction_id);
        }

        //=============2.7、盟主(代理)优惠买单支付佣金入账==================


        //=============2.8、平台收款=====================
        maccountService.maccountFlowConfirm(sn, transaction_id);

        //=============2.9、推荐会员佣金入账==================
        af = accountFlowService.selectOne(new EntityWrapper<AccountFlow>()
                .eq("sn", sn).eq("iotype", IotypeEnum.input.getVal()).eq("xftype", XftypeEnum.tuijianfan.getVal()));
        if (af != null) {
            //即时入账不需核销（优惠买单）
            accountService.accountFlowConfirm(order, af, transaction_id);
        }

        MerchantApp mapp = redisService.getMApp(order.getMpid());
        MconfigExt mconfigExt = mconfigExtService.selectById(order.getMpid());
        Maccount ma = maccountService.selectOne(new EntityWrapper<Maccount>().eq("mid", mid));
        logger.info("--------------------------------------mapp.getKefu1()=" + mapp.getKefu1());
        logger.info("--------------------------------------ma.getSmsmout()=" + ma.getSmsmout());
        logger.info("--------------------------------------mconfigExt=" + JSON.toJSONString(mconfigExt));
        //=================营销活动订单状态+商品库存状态处理=================
        //营销类型@-9：买单；-8：充值；  -2：券类订单；-1：积分购；0：普通商品； 1：拼团；2：砍价；3：抽奖；5：会员商品；6：预约抵扣项目；7：大礼包；8：秒杀；
        if (order.getType() != null && (
                order.getType().intValue() == YXType.jifen.getVal() ||      //-1：积分购
                        order.getType().intValue() == YXType.common.getVal() ||      //0：普通商品
                        order.getType().intValue() == YXType.pintuan.getVal() ||     //1：拼团
                        order.getType().intValue() == YXType.kanjia.getVal() ||      //2：砍价
                        order.getType().intValue() == YXType.choujiang.getVal() ||   //3：抽奖
                        order.getType().intValue() == YXType.hygoods.getVal() ||     //5：会员商品
                        order.getType().intValue() == YXType.dikou.getVal() ||       //6：预约抵扣项目
                        order.getType().intValue() == YXType.dalibao.getVal() ||     //7：大礼包
                        order.getType().intValue() == YXType.miaosha.getVal() ||     //8：秒杀
                        order.getType().intValue() == YXType.baoming.getVal() ||     //9：报名
                        order.getType().intValue() == YXType.toupiao.getVal() ||     //10：投票
                        order.getType().intValue() == YXType.jizan.getVal()          //13：集赞
        )) goodsAndOrderUpdate(order);

        //=================营销活动状态处理=================
        if (order.getType() != null && order.getType().intValue() == YXType.pintuan.getVal())
            pintuanUpdate(order);//1：拼团
        if (order.getType() != null && order.getType().intValue() == YXType.kanjia.getVal()) kanjiaUpdate(order);//2：砍价
        //如果是大礼包[7：大礼包]
        if (order.getType() != null && order.getType().intValue() == YXType.dalibao.getVal()) {
            AkkaServer.system.actorOf(Props.create(OrderActor.class))
                    .tell(Constants.AKKA_MSG_ORDER_DALIBAO + "@" + order.getId() + "@" + order.getGid() + "@" + uid, ActorRef.noSender());
        }
        //=============End营销活动订单处理End=================

        //触发返佣时机
        Boolean ruzhang = order.getFantimeType().intValue() == FantimeType.payok.getVal();

        //=============3、佣金结算=============
        //=============3.1、处理自购奖励，触发点在支付成功之后
        Goods goods = goodsService.selectById(order.getGid());

        if (goods != null && goods.getFantimeType() != null && FantimeType.payok.getVal() == goods.getFantimeType().intValue() &&
                (order.getFanjifen() != null && order.getFanjifen().doubleValue() > 0) ||
                (order.getFanqian() != null && order.getFanqian().doubleValue() > 0) ||
                (order.getFanbi() != null && order.getFanbi().doubleValue() > 0)) {
            zigouFan(order, FantimeType.payok.getVal(), ruzhang);
            //===待实现，自购返券

        } else {
            //全局定义的自购返属性定义
            //该逻辑废弃，统一在订单形成时计算
            //if (mconfig.getFantimeType() != null && mconfig.getFantimeType() == FantimeType.payok.getVal() &&
            //      ((order.getFanjifen() != null && order.getFanjifen().doubleValue() > 0) ||
            //              (order.getFanqian() != null && order.getFanqian().doubleValue() > 0) ||
            //              (order.getFanbi() != null && order.getFanbi().doubleValue() > 0))) {
            //                zigouFan(order);
            //}
        }

        //处理自购奖励返券
        //买单订单 goods==null
        //平台多商家版自购返，===待完善
        if (goods.getZgfanType() != null && mconfig.getFantimeType() == FantimeType.payok.getVal()) {
            //处理自购返券===待观察触发返券时机
            if (goods != null && goods.getZgfanType() != null &&
                    goods.getZgfanType().intValue() == XffanType.quan.getVal()) zigouFanquan(order);
        }

        //购买会员返券【特殊，配送小程序适配】<特殊>
        //支付购买立即触发
        if (order.getXftype().intValue() == XftypeEnum.buyHuiyuan.getVal()
                && !Strings.isNullOrEmpty(order.getTradecode())) {
            buyHuiyuanFan(order);
        }
        //=============End处理自购返End==========

        //=============3.2处理购买体验卡年卡类型
        //可能不是商品「自助买单」
        //支付购买立即触发
        if (goods != null && goods.getType() == YXType.quan.getVal() && goods.getTplid() != null
                && goods.getTplid().longValue() > 0) tiyanka(goods, order);
        //=============End处理购买体验卡年卡类型End

        //=============3.3检查购买会员商品
        logger.info("--------------------------------------start to check kaitong huiyuan");
        if (mconfig.getIsFenxiao() == 1 && order.getGid() != null) {
            logger.info("--------------------------------------start to check huiyuan 111");
            AkkaServer.system.actorOf(Props.create(OrderActor.class))
                    .tell(Constants.AKKA_MSG_HUIYUAN_SHENGJI + "@" + uid + "@hygoods" + "@" + order.getGid(), ActorRef.noSender());
        }

        //=============3.4推荐返佣《推荐者》
        //【普通分享奖励||多级分销返二选一，不能同时存在】
        //普通分享奖励，只返一级
        //非买单分享奖励，针对 gid>0
        //与订单一起生成，每笔订单对应一份奖励
        //order.getSharefan() >0  普通分享奖励模式
        //order.getFanqian()  >0  自购返
        logger.info("--------------------------------------start to check Sharefan");
        if (order.getSharefan() != null && order.getSharefan().doubleValue() > 0
                && order.getXftype().intValue() != XftypeEnum.smaidan.getVal()) {
            logger.info("--------------------------------------payConfirm order.getSharefan()=" + order.getSharefan());
            shareFan(order);//商品+活动 gid>0
        }

        //=============3.5平台优惠券买单分佣《推荐者》
        //支付购买立即触发
        if (order.getSharefan() != null && order.getSharefan().doubleValue() > 0
                && order.getCouponId() != null && order.getCouponId().doubleValue() > 0
                && order.getXftype().intValue() == XftypeEnum.smaidan.getVal()) {
            logger.info("--------------------------------------payConfirm order.shareSmaidanFan()=" + order.getMinprice());
            shareSmaidanFan(order);
        }

        //=============3.6优惠买单付款至商家《商家》
        if (order.getSid() != null && order.getSid().doubleValue() > 0
                && order.getType().intValue() == 0
                && order.getXftype().intValue() == XftypeEnum.smaidan.getVal()) {
            logger.info("--------------------------------------payConfirm order.smaidan");
//            saccountService.saccountFlowInConfirm(order, true);
            saccountService.addSamountInFlow(order, XftypeEnum.smaidan, true);
        }

        //=============3.7多级分销在fenxiaoFan处理《推荐者》
        //order.getFxe1()  >0  order.getFxe2()  >0
        logger.info("------------------------------------start to after Fenxiao");
        if (mconfig.getIsFenxiao() == 1 && order.getRealpay().doubleValue() > 0
                && order.getFxmode() != null && order.getFxmode() > 0) {
            logger.info("--------------------------------------start to check Fenxiao");
//            fenxiaoFan(order);
            AkkaServer.system.actorOf(Props.create(FenxiaoActor.class))
                    .tell((order.getType().intValue() == YXType.hygoods.getVal() ? Constants.AKKA_MSG_ORDER_FENXIAO_HUIYUAN : Constants.AKKA_MSG_ORDER_FENXIAO_XIAOFEI) + "@" + order.getId(), ActorRef.noSender());
        }

        logger.info(">>>>>>payConfirm qnpay.payPakect start");

        //=============3.8平台版付款至商家（收款）《商家》
        //针对恰恰全积分支付码开发《特殊》
        //系统需满足秒到账配置
        //买单收款默认秒到===待完善
        if (order.getXftype().intValue() == XftypeEnum.maidan.getVal() && order.getSid() != null && order.getSid() > 0
                && !Strings.isNullOrEmpty(order.getTradecode()) && order.getRealpay().doubleValue() >= 0
                && order.getTradecode().startsWith("ma=") && mconfig.getIsAutofan().intValue() == 1) {
            logger.info("----------------payConfirm qnpay.payPakect coming");
            //转账至商家

            String key = order.getMid() + mapp.getAppid() + order.getMpid();
            String txt = AesUtil.decrypt(order.getTradecode().substring(3), EncryptUtil.md5t16(key));
            String[] ywdata = txt.split("__");

            User touser = redisService.getUserByGuid(ywdata[2]);

            Map<String, Object> paymap = qnpay.payPakect(order.getMpid(), mapp.getAppid(), touser, order.getRealpay(), "用户到店买单付款至商户", "127.0.0.1");
            if (paymap.containsKey("result_code") && paymap.get("result_code").toString().equals("SUCCESS")) {
                addAccountFlow(touser, order.getRealpay(), true, 1, order, IotypeEnum.output, XftypeEnum.withdraw);
            }
        }

        //=============3.9营销活动商品支付
        //营销活动统统针对商家
        //商家卖货，钱先到账至待入账金额里
        if (order.getType().intValue() >= 0 && order.getSid() != null && order.getSid().longValue() > 0
                && order.getMinprice() != null && order.getMinprice().doubleValue() >= 0) {//商家促销成本
            logger.info("-------------------------------payConfirm to muser account fanliing");
            //转账至商家
            orderStorePay(order, ruzhang, order.getMinprice());
        }

        //=============4.0联盟收益
        if (order.getType().intValue() >= 0 && order.getSid() != null && order.getSid().longValue() > 0
                && order.getLmfan() != null && order.getLmfan().doubleValue() >= 0) {
            //联盟收益
            logger.info("-------------------------------payConfirm to orderAgentPay account fanliing");
            //转账至盟主佣金
            orderAgentPay(order, ruzhang, order.getLmfan());
        }

        //=============4.1平台净收益
        if (order.getPtfan() != null && order.getPtfan().doubleValue() >= 0) {
            //平台净收益
            logger.info("-------------------------------payConfirm to orderPlatformPay account fanliing");
            //转账至盟主佣金
            orderPlatformPay(order, ruzhang);
        }

        //=============End佣金结算=============

        //=============4、通知+提醒+人气+其他=============
        //=============4.1、订单短信提醒
        //默认只给客服1发订单短信提醒
        String tophone = mapp.getKefu1();
        if (!Strings.isNullOrEmpty(mapp.getKefu1()) && ma.getSmsmout() != null && ma.getSmstotal().intValue() > 0
                && mconfigExt != null && mconfigExt.getSmstplid() != null) {
            User user = userService.selectById(order.getUid());
            //买单短信提醒
            if (order.getXftype() == XftypeEnum.maidan.getVal() && !Strings.isNullOrEmpty(user.getPhone())) {

                Account accout = accountService.selectOne(new EntityWrapper<Account>().eq("uid", order.getUid()));
                String sms = String.format("消费提醒：亲爱的会员您好，您于%s通过小程序自助买单服务，成功消费%s元，会员余额%s元，如果不是您本人操作，请咨询%s客服热线%s。",
                        DateUtil.toDateString(order.getCreatetime(), "yyyy年MM月dd日 hh:mm:ss"), order.getTotal(), accout.getTotal(), mapp.getName(), mapp.getKefuzj());
                String[] param = {DateUtil.toDateString(order.getCreatetime(), "yyyy年MM月dd日 hh:mm:ss"), order.getTotal().toString(), accout.getTotal().toString(), mapp.getName(), mapp.getKefuzj()};
                smslogService.sendOnetplsms(user.getPhone(), sms, param, mconfigExt.getSmstplidxf(), mid, mpid, sid, oid);
            }
            if (sid != null) {
                if (store.getPhone() != null && RegexUtil.REGEX_SHOUJIHAO.matcher(store.getPhone()).find()) {
                    tophone = store.getPhone();
                } else {
                    User muser = userService.selectOne(new EntityWrapper<User>()
                            .setSqlSelect("id,phone")
                            .eq("sid", sid).eq("is_mch", 1).eq("is_admin", 1));
                    if (muser != null && muser.getPhone() != null) tophone = muser.getPhone();
                }
            }

            if (order.getType() == 0 && order.getGtype() == 3 && !Strings.isNullOrEmpty(order.getYytime())) {
                //短信提醒
                AkkaServer.system.actorOf(Props.create(SmsActor.class))
                        .tell(Constants.AKKA_MSG_SMS_YUYUE + "@" + order.getUid() + "@" + order.getId(), ActorRef.noSender());
                //预约奖励
                AkkaServer.system.actorOf(Props.create(FanActor.class))
                        .tell(Constants.AKKA_MSG_YUYUE + "@" + order.getUid() + "@" + order.getMpid() + "@" + order.getId(), ActorRef.noSender());
            } else if (order.getType() >= 0) {
                //订单短信提醒(通用模板)
                String sms = String.format("订单通知：%s门店用户%s(%s)已下单购买%s等，请尽快处理", mapp.getName(), order.getLinkman(), order.getPhone(), order.getGoodsName());
                String[] param = {mapp.getName(), order.getLinkman(), order.getPhone(), order.getGoodsName()};

                smslogService.sendOnetplsms(tophone, sms, param, mconfigExt.getSmstplid(), mid, mpid, sid, oid);
            }
        }
        //======================END订单短信提醒END==================

        //=============4.2、如果是需要发货的订单，向商户端发货通知
        if (order.getGtype() == 1) {
            AkkaServer.system.actorOf(Props.create(OrderActor.class))
                    .tell(Constants.AKKA_MSG_ORDER_NOTIFY + "@" + order.getId() + "@" + uid, ActorRef.noSender());
        }

        //=============4.3、处理店铺商家人气
        if (order.getSid() != null) {
            AkkaServer.system.actorOf(Props.create(StoreActor.class))
                    .tell(Constants.AKKA_MSG_STORE_ORDER + "@" + order.getSid(), ActorRef.noSender());
        }
        //=============END处理店铺商家人气

        //=============5、其他=============
        //牛财多会员买单
        shymaidanOrder(order);

        //套餐活动关联产品自动购买
        if (goods.getGtype().intValue() == GtypeEnum.daodian.getVal()
                && goods.getLogisticsId().longValue() > 0) {
            autoOrder(goods, order);
        }


        //开始打印小票
        if (store != null && store.getIsprint() != null && store.getIsprint() == 1) {

            logger.debug("---------------start to print-------------");
//          String purl = "https://open-api.10ss.net/oauth/authorize?response_type=code&client_id=1033889752&redirect_uri=https%3a%2f%2fniucaiduo.com%2fprint%2fcallback&state=1";
//          String code = HttpUtils.httpGet(purl);
//          String code = "9dbf2099086b498c95e97f30b84112d7";

            String machineCode = "4004668858";

            String mckey = Constants.REDIS_PRINTER_CODE + machineCode;
            String mckeyinit = Constants.REDIS_PRINTER_INIT + machineCode;

            String code = redisService.get(mckey);
            Integer init = redisService.get(mckeyinit);

            if (Strings.isNullOrEmpty(code)) return;

            logger.debug("=========================code=" + code);

            if (init == null) {
                logger.debug("=========================init == null");
                Methods.getInstance().init("1033889752", "4fd969cddf2e9e23d157030176ce7f1a", code);
                Methods.getInstance().getToken();
                redisService.set(mckeyinit, 1);
            } else if (Strings.isNullOrEmpty(Methods.CLIENT_ID)) {
                logger.debug("=========================Strings.isNullOrEmpty(Methods.CLIENT_ID)");
                Methods.getInstance().init("1033889752", "4fd969cddf2e9e23d157030176ce7f1a", code);
                Methods.getInstance().getToken();
            }

            String pcontent = "<center><FS>谊品生鲜订单</FS></center>\r\r" +
                    "订单编号：" + order.getOrderNo() + "\r" +
                    "支付方式：" + (order.getPayType() == 0 ? "无支付" : order.getPayType() == 1 ? "货到付款" : order.getPayType() == 2 ? "微信支付" : order.getPayType() == 3 ? "余额支付" : "") + "\r" +
                    "快递方式：" + (order.getShipperMethod() == 4 ? "自提" : order.getShipperMethod() == 1 ?
                    order.getShipperName() : order.getShipperMethod() == 2 ? "外卖配送" : order.getShipperMethod() == 3 ? "商家配送" : "无配送") + "\r" +
                    "<FS>收货人：" + order.getLinkman() + "</FS>\r" +
                    "<FS>收货电话：" + order.getPhone() + "</FS>\r" +
                    "收货地址：" + order.getAddress() + "\r" +
                    "下单时间：" + DateUtil.toDateString(order.getCreatetime(), "yyyy-MM-dd HH:mm:ss") + "\r\r" +
                    "<table>" +
                    "<tr><td>品名</td><td>数量</td><td>价格</td></tr>";

            List<OrderGoods> ogoods = orderGoodsService.selectList(new EntityWrapper<OrderGoods>().eq("oid", order.getId()));
//            for (OrderGoods item : ogoods) {
//                pcontent += "<tr><td>" + item.getGoodsName() + "</td><td>" + item.getNumber() + "</td><td>" + item.getSaleprice() + "</td></tr>";
//            }
            pcontent += "<tr><td>雪花啤酒</td><td>6</td><td>4.5</td></tr>";
            pcontent += "<tr><td>酒鬼花生</td><td>2</td><td>7.9</td></tr>";
//            pcontent += "</table>" +
//                    "\r\r" +
//                    "备注：" + (order.getRemark() == null ? "" : order.getRemark()) + "\r\r" +
//                    "<right>总计：" + order.getTotal() + "</right>" +
//                    "<right>实付：" + order.getRealpay() + "</right>\r";

            pcontent += "</table>" +
                    "\r\r" +
                    "备注：" + (order.getRemark() == null ? "" : order.getRemark()) + "\r\r" +
                    "<right>总计：42.8</right>" +
                    "<right>实付：42.8</right>\r";


            logger.info("--------------------------------------payConfirm over");
            Methods.getInstance().print("4004668858", pcontent, "4004668858");
        }

        logger.info("--------------------------------------payConfirm over");
    }

    //商家卖货收款
    private void orderStorePay(Order order, boolean ruzhang, BigDecimal minprice) {

        logger.debug("======orderStorePay coming for order =" + JSON.toJSONString(order));
        if (order.getSid() == null || order.getSid().longValue() == 0) {
            logger.debug("======orderStorePay order.getSid() =" + order.getSid());
            return;
        }

        Mdpay mdpay = mdpayMapper.selectById(-order.getMpid());
        BigDecimal zero = new BigDecimal(0);
        //非盟主模式非联盟模式
        if (mdpay == null) {

            //入账到商家总管理员账户
            User user = userService.selectOne(new EntityWrapper<User>()
                    .eq("is_mch", 1).eq("is_admin", 1).eq("sid", order.getSid()));

            if (user == null) {
                logger.debug("==================orderStorePay cannt found muser for sid=" + order.getSid());
                return;
            }

            Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", user.getId()));
            if (act == null) {
                act = accountService.initAccount(user.getId(), user.getMid(), user.getMpid());
            }

            AccountFlow af = new AccountFlow();
            //营销成本付给商家，对于商家来说是入账，
            //可用金额，所以设置 setAmount 这个字段
            af.setAmount(minprice);
            af.setDikou(zero);//对应营销金额
            af.setRealpay(zero);
            af.setTotal(minprice);

            af.setSn(order.getOrderNo());
            af.setIotype(IotypeEnum.input.getVal());//商家个人账户入账
            af.setXftype(XftypeEnum.sell.getVal());//对笔流水对于商家是卖货

            af.setNickname(user != null ? user.getNickName() : null);
            af.setHeadimg(user != null ? user.getAvatarPic() : null);
            af.setPhone(user != null ? user.getPhone() : null);

            af.setIsConfirm(-1);
            af.setState(1);

            af.setTradetime(order.getCreatetime());
            af.setCreatetime(af.getTradetime());
            af.setRemark(XftypeEnum.sell.getName());
            af.setMid(order.getMid());
            af.setMpid(order.getMpid());
            af.setUid(user.getId());
            af.setLasttotal(act.getTotal());
            af.setLastamount(act.getAmount());
            af.insert();

            boolean flag = false;
            Account naccount = new Account();
            while (!flag) {

                af.setTransactionid(order.getTransactionId());
                af.setIsConfirm(1);
                af.setRuzhang(ruzhang ? 1 : -1);
                af.setConfirmDate(new Date());

                Long version = act.getVersion();

                BigDecimal total = act.getTotal();
                BigDecimal amount = act.getAmount();
                BigDecimal fanliing = act.getFanliing();
                BigDecimal unuseAmount = act.getUnuseAmount();

                //========商家卖货收款======
                //不计入佣金
                naccount.setTotal(total.add(af.getRealpay()).add(af.getAmount()));
                if (ruzhang) {
                    naccount.setAmount(amount.add(af.getAmount()));
                } else {
                    naccount.setUnuseAmount(unuseAmount.add(af.getAmount()));
                    naccount.setFanliing(fanliing.add(af.getAmount()));
                }

                naccount.setModifytime(new Date());
                naccount.setModifier(user.getId());

                naccount.setMid(af.getMid());
                naccount.setMpid(af.getMpid());
                naccount.setVersion(version + 1);

                flag = accountService.update(naccount, new EntityWrapper<Account>()
                        .eq("uid", user.getId()).eq("version", version));

                if (flag) af.insertOrUpdate();

                act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", user.getId()));
            }
        } else {
            saccountService.addSamountInFlow(order, XftypeEnum.sell, true);
        }
    }

    //商家卖货（营销活动成交）盟主收佣金，需要核销
    //商家卖货（营销活动成交）盟主收佣金收佣金，需要核销
    private void orderAgentPay(Order order, boolean ruzhang, BigDecimal price) {

        logger.debug("======orderAgentPay coming for order =" + JSON.toJSONString(order));
        if (order.getLeagueid() == null || order.getLeagueid().longValue() == 0) {
            logger.debug("======orderAgentPay order.getSid() =" + order.getSid());
            return;
        }

        //入账到代理|盟主管理员账户
        User user = userService.getLeagueUserbyLeagueid(order.getLeagueid());
        if (user == null) {
            logger.debug("==================orderAgentPay cannt found muser for sid=" + order.getSid());
            return;
        }
        Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", user.getId()));
        if (act == null) {
            act = accountService.initAccount(user.getId(), user.getMid(), user.getMpid());
        }

        BigDecimal zero = new BigDecimal(0);

        AccountFlow af = new AccountFlow();
        //营销成本付给商家，对于商家来说是入账，
        //可用金额，所以设置 setAmount 这个字段
        af.setAmount(price);
        af.setDikou(zero);//对应营销金额
        af.setRealpay(zero);
        af.setTotal(price);

        af.setSn(order.getOrderNo());
        af.setFantimeType(ruzhang ? FantimeType.payok.getVal() : FantimeType.hexiao.getVal());
        af.setIotype(IotypeEnum.input.getVal());
        af.setXftype(XftypeEnum.ashoukuan.getVal());//对笔流水对于盟主是佣金
        af.setXftypename(XftypeEnum.ashoukuan.getName());//对笔流水对于盟主是佣金

        af.setNickname(user != null ? user.getNickName() : null);
        af.setHeadimg(user != null ? user.getAvatarPic() : null);
        af.setPhone(user != null ? user.getPhone() : null);

        af.setIsConfirm(-1);
        af.setState(1);

        af.setTradetime(order.getCreatetime());
        af.setCreatetime(af.getTradetime());
        af.setRemark(XftypeEnum.ashoukuan.getName());
        af.setMid(order.getMid());
        af.setMpid(order.getMpid());
        af.setSid(order.getSid());
        af.setLeagueid(order.getLeagueid());
        af.setUid(user.getId());
        af.setLasttotal(act.getTotal());
        af.setLastamount(act.getAmount());
        af.insert();

        boolean flag = false;
        Account naccount = new Account();
        while (!flag) {


            af.setTransactionid(order.getTransactionId());
            af.setIsConfirm(1);
            af.setRuzhang(ruzhang ? 1 : -1);
            af.setConfirmDate(new Date());

            Long version = act.getVersion();

            BigDecimal total = act.getTotal();
            BigDecimal amount = act.getAmount();
            BigDecimal fanliing = act.getFanliing();
            BigDecimal fanli = act.getFanli();
            BigDecimal unuseAmount = act.getUnuseAmount();

            //========商家卖货收款======
            //========凡是佣金，需要触发《入账》之后才算是【累计佣金】
            naccount.setTotal(total.add(af.getRealpay()).add(af.getAmount()));
            if (ruzhang) {
                naccount.setAmount(amount.add(af.getAmount()));
                naccount.setFanli(fanli.add(af.getAmount()));
            } else {
                naccount.setUnuseAmount(unuseAmount.add(af.getAmount()));
                naccount.setFanliing(fanliing.add(af.getAmount()));
            }

            naccount.setModifytime(new Date());
            naccount.setModifier(user.getId());

            naccount.setMid(af.getMid());
            naccount.setMpid(af.getMpid());
            naccount.setVersion(version + 1);

            flag = accountService.update(naccount, new EntityWrapper<Account>()
                    .eq("uid", user.getId()).eq("version", version));

            if (flag) af.insertOrUpdate();

            act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", user.getId()));
        }
    }

    //平台佣金
    private void orderPlatformPay(Order order, boolean ruzhang) {

        logger.debug("======orderPlatformPay coming for order =" + JSON.toJSONString(order));
        if (order.getPtfan() == null || order.getPtfan().longValue() == 0) {
            logger.debug("======orderPlatformPay order.getPtfan() =" + order.getPtfan());
            return;
        }

        //入账到代理|盟主管理员账户
        User user = userService.getAdminUser(order.getMpid());
        if (user == null) {
            logger.debug("==================orderPlatformPay cannt found muser for sid=" + order.getSid());
            return;
        }

        Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", user.getId()));
        if (act == null) {
            act = accountService.initAccount(user.getId(), user.getMid(), user.getMpid());
        }
        BigDecimal zero = new BigDecimal(0);
        AccountFlow af = new AccountFlow();
        //营销成本付给商家，对于商家来说是入账，
        //可用金额，所以设置 setAmount 这个字段
        af.setAmount(order.getPtfan());
        af.setDikou(zero);//对应营销金额
        af.setRealpay(zero);
        af.setTotal(order.getPtfan());

        af.setSn(order.getOrderNo());
        af.setTransactionid(order.getTransactionId());
        af.setIotype(IotypeEnum.input.getVal());
        af.setXftype(XftypeEnum.platyongjin.getVal());//对笔流水对于盟主是佣金
        af.setXftypename(XftypeEnum.platyongjin.getName());//对笔流水对于盟主是佣金

        af.setNickname(user != null ? user.getNickName() : null);
        af.setHeadimg(user != null ? user.getAvatarPic() : null);
        af.setPhone(user != null ? user.getPhone() : null);

        af.setIsConfirm(-1);
        af.setState(1);

        af.setTradetime(order.getCreatetime());
        af.setCreatetime(af.getTradetime());
        af.setRemark(XftypeEnum.platyongjin.getName());
        af.setMid(order.getMid());
        af.setMpid(order.getMpid());
        af.setUid(user.getId());
        af.setLasttotal(act.getTotal());
        af.setLastamount(act.getAmount());
        af.insert();

        boolean flag = false;
        Account naccount = new Account();
        while (!flag) {


            af.setTransactionid(order.getTransactionId());
            af.setRuzhang(ruzhang ? 1 : -1);
            af.setIsConfirm(1);
            af.setConfirmDate(new Date());

            Long version = act.getVersion();

            BigDecimal total = act.getTotal();
            BigDecimal amount = act.getAmount();
            BigDecimal fanliing = act.getFanliing();
            BigDecimal fanli = act.getFanli();
            BigDecimal unuseAmount = act.getUnuseAmount();

            //========平台佣金======
            naccount.setTotal(total.add(af.getRealpay()).add(af.getAmount()));
            if (ruzhang) {
                naccount.setAmount(amount.add(af.getAmount()));
                naccount.setFanli(fanli.add(af.getAmount()));
            } else {
                naccount.setUnuseAmount(unuseAmount.add(af.getAmount()));
                naccount.setFanliing(fanliing.add(af.getAmount()));
            }

            naccount.setModifytime(new Date());
            naccount.setModifier(user.getId());

            naccount.setMid(af.getMid());
            naccount.setMpid(af.getMpid());
            naccount.setVersion(version + 1);

            flag = accountService.update(naccount, new EntityWrapper<Account>()
                    .eq("uid", user.getId()).eq("version", version));

            if (flag) af.insertOrUpdate();
            act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", user.getId()));
        }
    }

    //商家卖货入账，不算做佣金，入平台账户|核销扫码触发
    private void orderStorePayRuzhang(String oid) {

        Order order = orderService.selectById(oid);
        logger.debug("======orderStorePayRuzhang coming for order =" + JSON.toJSONString(order));
        if (order == null || order.getSid() == null || order.getSid().longValue() == 0) {
            logger.debug("======orderStorePayRuzhang order.getSid() =" + order.getSid());
            return;
        }

        Mdpay mdpay = mdpayMapper.selectById(-order.getMpid());
        BigDecimal zero = new BigDecimal(0);
        //非盟主模式非联盟模式
        if (mdpay == null) {

            User user = userService.selectOne(new EntityWrapper<User>()
                    .eq("is_mch", 1).eq("is_admin", 1)
                    .eq("sid", order.getSid()));
            logger.debug("---------------orderStorePayRuzhang  user =" + JSON.toJSONString(user));
            if (user == null) {
                logger.debug("------------orderStorePayRuzhang user cannt found muser for sid=" + order.getSid());
                return;
            }
            Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", user.getId()));
            AccountFlow af = accountFlowService.selectOne(new EntityWrapper<AccountFlow>()
                    .eq("sn", order.getOrderNo()).eq("xftype", XftypeEnum.sell.getVal()));
            logger.debug("---------------------------orderStorePayRuzhang  af =" + JSON.toJSONString(af));

            if (af == null) {
                logger.debug("---------------------------orderStorePayRuzhang af cannt found muser for sid=" + order.getSid());
                return;
            }

            boolean flag = false;
            Account naccount = new Account();
            while (!flag) {
                //商家卖货入账，不算做佣金
                Long touid = af.getUid();

                Long version = act.getVersion();
                BigDecimal amount = act.getAmount();
                BigDecimal fanliing = act.getFanliing();
//                BigDecimal fanli = act.getFanli();//卖货不算入佣金额，属于销售额
                BigDecimal unuseAmount = act.getUnuseAmount();

//                naccount.setFanli(fanli.add(af.getAmount()));

                naccount.setAmount(amount.add(af.getAmount()));
                naccount.setUnuseAmount(unuseAmount.subtract(af.getAmount()));
                naccount.setFanliing(fanliing.subtract(af.getAmount()));

                naccount.setModifytime(new Date());
                naccount.setModifier(touid);
                naccount.setVersion(version + 1);

                af.setRuzhang(1);


                flag = accountService.update(naccount, new EntityWrapper<Account>().eq("uid", touid).eq("version", version));
                if (flag) {
                    af.updateById();
                    Long ruzhangid = af.getId();
                    af.setId(null);

                    af.setTransactionid(ruzhangid.toString());
                    af.setTotal(zero);
                    af.setRealpay(zero);
                    af.setAmount(zero);
                    af.setDikou(zero);
                    af.setIotype(0);
                    af.setIsConfirm(1);
                    af.setRuzhang(0);
                    af.setXftype(XftypeEnum.ruzhang.getVal());
                    af.setXftypename(XftypeEnum.ruzhang.getName());
                    af.setCreatetime(new Date());
                    af.setConfirmDate(new Date());
                    af.setLasttotal(act.getTotal());
                    af.setLastamount(act.getAmount());
                    af.insert();
                }

                act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", user.getId()));
            }
        } else {
            //核销触发入账至商家《卖货收入》
            saccountService.addSamountRuzhangFlow(order);
        }
    }

    //商家卖货入账，不算做佣金，入平台账户|核销扫码触发
    private void orderMengzhuPayRuzhang(String oid) {

        Order order = orderService.selectById(oid);
        logger.debug("======orderMengzhuPayRuzhang coming for order =" + JSON.toJSONString(order));
        if (order == null || order.getLmfan() == null || order.getLmfan().doubleValue() == 0 ||
                order.getLeagueid() == null || order.getLeagueid().longValue() == 0) {
            logger.debug("======orderMengzhuPayRuzhang order.getLmfan() =" + order.getLmfan());
            return;
        }

        User user = userService.getLeagueUserbyLeagueid(order.getLeagueid());
        logger.debug("---------------------------orderMengzhuPayRuzhang  user =" + JSON.toJSONString(user));
        if (user == null) {
            logger.debug("======orderMengzhuPayRuzhang user cannt found muser for sid=" + order.getSid());
            return;
        }
        Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", user.getId()));
        AccountFlow af = accountFlowService.selectOne(new EntityWrapper<AccountFlow>()
                .eq("sn", order.getOrderNo()).eq("xftype", XftypeEnum.ashoukuan.getVal()).eq("uid", user.getId()));
        logger.debug("---------------------------orderMengzhuPayRuzhang  af =" + JSON.toJSONString(af));

        if (af == null) {
            logger.debug("---------------------------orderMengzhuPayRuzhang af cannt found muser for sid=" + order.getSid());
            return;
        }

        BigDecimal zero = new BigDecimal(0);
        boolean flag = false;
        Account naccount = new Account();
        while (!flag) {
            //盟主佣金直接入账
            Long touid = af.getUid();

            Long version = act.getVersion();
            BigDecimal amount = act.getAmount();
            BigDecimal fanliing = act.getFanliing();
            BigDecimal fanli = act.getFanli();
            BigDecimal unuseAmount = act.getUnuseAmount();

            //赋值
            naccount.setAmount(amount.add(af.getAmount()));
            naccount.setFanli(fanli.add(af.getAmount()));

            naccount.setUnuseAmount(unuseAmount.subtract(af.getAmount()));
            naccount.setFanliing(fanliing.subtract(af.getAmount()));

            naccount.setModifytime(new Date());
            naccount.setModifier(touid);
            naccount.setVersion(version + 1);

            af.setRuzhang(1);
            af.setModifytime(new Date());
            af.setModifier(0l);//系统更改

            flag = accountService.update(naccount, new EntityWrapper<Account>().eq("uid", touid).eq("version", version));
            if (flag) {
                af.updateById();
                Long ruzhangid = af.getId();
                af.setId(null);

                af.setTransactionid(ruzhangid.toString());
                af.setTotal(zero);
                af.setRealpay(zero);
                af.setAmount(zero);
                af.setDikou(zero);
                af.setIotype(0);
                af.setXftype(XftypeEnum.ruzhang.getVal());
                af.setXftypename(XftypeEnum.ruzhang.getName());
                af.setCreatetime(new Date());
                af.setIsConfirm(1);
                af.setRuzhang(0);
                af.setConfirmDate(new Date());
                af.setLasttotal(act.getTotal());
                af.setLastamount(act.getAmount());
                af.insert();
            }

            act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", user.getId()));
        }
    }

    //商家卖货入账，不算做佣金，入平台账户|核销扫码触发
    private void orderPlatformPayRuzhang(String oid) {

        Order order = orderService.selectById(oid);
        logger.debug("======orderPlatformPayRuzhang coming for order =" + JSON.toJSONString(order));
        if (order == null || order.getLmfan() == null || order.getLmfan().doubleValue() == 0 ||
                order.getSid() == null || order.getSid().longValue() == 0) {
            logger.debug("======orderPlatformPayRuzhang order.getLmfan() =" + order.getLmfan());
            return;
        }

        User user = userService.getAdminUser(order.getMpid());
        logger.debug("---------------------------orderPlatformPayRuzhang  user =" + JSON.toJSONString(user));
        if (user == null) {
            logger.debug("======orderPlatformPayRuzhang user cannt found muser for sid=" + order.getSid());
            return;
        }
        Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", user.getId()));
        AccountFlow af = accountFlowService.selectOne(new EntityWrapper<AccountFlow>()
                .eq("sn", order.getOrderNo()).eq("xftype", XftypeEnum.platyongjin.getVal()).eq("uid", user.getId()));
        logger.debug("---------------------------orderPlatformPayRuzhang  af =" + JSON.toJSONString(af));

        if (af == null) {
            logger.debug("---------------------------orderPlatformPayRuzhang af cannt found muser for sid=" + order.getSid());
            return;
        }

        BigDecimal zero = new BigDecimal(0);
        boolean flag = false;
        Account naccount = new Account();
        while (!flag) {
            //盟主佣金直接入账
            Long touid = af.getUid();

            Long version = act.getVersion();
            BigDecimal amount = act.getAmount();
            BigDecimal fanliing = act.getFanliing();
            BigDecimal fanli = act.getFanli();
            BigDecimal unuseAmount = act.getUnuseAmount();

            naccount.setAmount(amount.add(af.getAmount()));
            naccount.setFanli(fanli.add(af.getAmount()));

            naccount.setUnuseAmount(unuseAmount.subtract(af.getAmount()));
            naccount.setFanliing(fanliing.subtract(af.getAmount()));

            naccount.setModifytime(new Date());
            naccount.setModifier(touid);
            naccount.setVersion(version + 1);

            af.setLasttotal(act.getTotal());
            af.setLastamount(act.getAmount());
            flag = accountService.update(naccount, new EntityWrapper<Account>().eq("uid", touid).eq("version", version));
            if (flag) {
                af.setId(null);

                af.setTotal(zero);
                af.setRealpay(zero);
                af.setAmount(zero);
                af.setDikou(zero);
                af.setXftype(XftypeEnum.ruzhang.getVal());
                af.setXftypename(XftypeEnum.ruzhang.getName());
                af.setCreatetime(new Date());
                af.setConfirmDate(new Date());
                af.insert();
            }

            act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", user.getId()));
        }
    }

    //充值确认
    public void rechargeConfirm(String sn, String transactionid, String paytime) {
        logger.debug("--------------------------------------rechargeConfirm sn=" + sn + " transactionid=" + transactionid);
        //更新订单状态
        boolean flag = false;
        MaccountFlow maf = maccountFlowService.selectOne(new EntityWrapper<MaccountFlow>().eq("sn", sn));

        AccountFlow af = accountFlowService.selectOne(new EntityWrapper<AccountFlow>().eq("sn", sn));
        Long uid = af.getUid();
        Long mid = af.getMid();
        Long mpid = af.getMpid();

        logger.debug("--------------------------------------rechargeConfirm maf=" + JSON.toJSONString(maf));
        logger.debug("--------------------------------------rechargeConfirm af=" + JSON.toJSONString(af));
        if (maf != null) {

            flag = false;
            Maccount maccount = new Maccount();//充值确认+累计销售额
            while (!flag) {
                Maccount ma = maccountService.selectOne(new EntityWrapper<Maccount>().eq("mid", mid));
                if (ma == null) {
                    ma = maccountService.initMaccount(uid, mid);
                }
                maf.setTransactionid(transactionid);
                maf.setIsConfirm(1);
                maf.setConfirmDate(new Date());
                maf.setLasttotal(ma.getTotal());

                Long version = ma.getVersion();

                BigDecimal amount = ma.getAmount();
                BigDecimal total = ma.getTotal();
                BigDecimal charget = ma.getChargeAmount();
                BigDecimal sale = ma.getSaleAmount();
                BigDecimal market = ma.getMamount();

                maccount.setTotal(maf.getAmount().add(total));      //总金额
                maccount.setSaleAmount(maf.getAmount().add(sale));  //累计销售额度

                if (af == null) maccount.setChargeAmount(maf.getAmount().add(charget));//客户充值=商家销售||客户为空=平台自己充值
                maccount.setAmount(maf.getAmount().add(amount));    //可用余额
                maccount.setMamount(maf.getMamount().add(market));  //营销总金额

                maccount.setModifytime(new Date());
                maccount.setVersion(version + 1);

                flag = maccountService.update(maccount, new EntityWrapper<Maccount>().eq("id", ma.getId()).eq("version", version));
                logger.debug("----------------maccountService.update flag=" + flag);
                if (flag) {
                    flag = maf.insertOrUpdate();
                    logger.debug("------------------maf.insertOrUpdate() flag=" + flag);
                }
            }
        }

        //更新用户账户信息
        Order order = orderService.selectOne(new EntityWrapper<Order>().eq("order_no", sn));
        Order norder = new Order();
        norder.setId(order.getId());
        norder.setStatus(StatusEnum.finish.getVal());
        norder.setOkday(DateUtil.getToday());
        norder.setFhstate(3);
        norder.setPaytime(DateUtil.toDate(paytime, "yyyyMMddhhmmss"));
        norder.setModifytime(new Date());
        norder.setModifier(0l);
        norder.updateById();

        OrderGoods og = new OrderGoods();
        og.setFhstate(3);
        og.setStatus(StatusEnum.finish.getVal());
        og.setState(1);
        og.setModifytime(new Date());
        og.setModifier(order.getUid());
        og.setPaytime(new Date());
        og.setOkday(DateUtil.getToday());
        orderGoodsService.update(og, new EntityWrapper<OrderGoods>().eq("oid", order.getId()));

        //=============3.9营销活动商品支付
        //营销活动统统针对商家
        //商家卖货，钱先到账至待入账金额里
        if (order.getType().intValue() >= 0 && order.getSid() != null && order.getSid().longValue() > 0
                && order.getMinprice() != null && order.getMinprice().doubleValue() >= 0) {//商家促销成本
            logger.info("-------------------------------payConfirm to muser account fanliing");
            //转账至商家
            orderStorePay(order, true, order.getMinprice());
        }

        accountService.accountFlowConfirm(order, af, transactionid);

        //更新积分
        logger.debug("--------------------------------------rechargeConfirm jf confirm");
        jifenService.jifenFlowConfirm(sn, uid);

        //更新币
        xnbiService.xnbiFlowConfirm(sn, uid);

        logger.debug("--------------------------------------------start to send templatemsg");

        //发送模板消息 OK
        Templatemsg templatemsg = templatemsgService.selectOne(new EntityWrapper<Templatemsg>()
                .eq("tplcode", "recharge")
                .eq("mpid", af.getMpid())
                .orderBy("id"));

        User user = userService.selectOne(new EntityWrapper<User>()
                .setSqlSelect("id,openid,phone")
                .eq("id", uid));
        //tplform save formid
        Tplform tplform = new Tplform();
        tplform.setMid(mid);
        tplform.setMpid(mpid);
        tplform.setOpenid(user.getOpenid());
        tplform.setFormid(order.getPrepayid());
        tplform.setFormdate(DateUtil.toDateString(order.getCreatetime(), "yyyy-MM-dd"));
        tplform.setState(1);
        tplform.insert();

        tplform.setId(null);
        tplform.insert();
        tplform.setId(null);
        tplform.insert();

        if (templatemsg != null && !Strings.isNullOrEmpty(templatemsg.getTplid())) {


//            Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", uid));

//            List<TemplateData> tpllist = new ArrayList<TemplateData>();

//            tpllist.add(new TemplateData("keyword1", templatemsg.getKeyname1()));
//            tpllist.add(new TemplateData("keyword2", DateUtil.toDateString(order.getCreatetime(), "yyyy年MM月dd日 hh:mm:ss")));
//            tpllist.add(new TemplateData("keyword3", order.getRealpay().toString() + "元"));
//            tpllist.add(new TemplateData("keyword4", account.getTotal().doubleValue() + "元"));
//            tpllist.add(new TemplateData("keyword5", jifen.getTotal().toString()));

//            WxmappTemplate wxtpl = new WxmappTemplate();
//            wxtpl.setTouser(tplform.getOpenid());
//            wxtpl.setForm_id(tplform.getFormid());
//
//            wxtpl.setTemplate_id(templatemsg.getTplid());
//            wxtpl.setPage(templatemsg.getPage());
//            wxtpl.setTemplateDataList(tpllist);

//            ObjectUtil.sendTemplateMsg(redisService.getWxtoken(mpid.toString()), wxtpl);

//           redisService.set(tplform.getFormid(),wxtpl);
//           ActorRef wxtemplateActor = AkkaServer.system.actorOf(Props.create(WxtemplateActor.class));
//           FiniteDuration duration = FiniteDuration.apply(3, TimeUnit.SECONDS);//10后发送
//           AkkaServer.system.scheduler().scheduleOnce(duration,wxtemplateActor, tplform.getMpid().toString()+"@"+tplform.getFormid(),AkkaServer.system.dispatcher(),ActorRef.noSender());

//            tplform.setState(-1);
//            tplform.setModifytime(new Date());
//            tplform.updateById();
        }

//        如有绑定手机，则短信通知
        Account account = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
        logger.debug("======orderNotify send tplmsg ok for user phone=" + user.getPhone());
        if (!Strings.isNullOrEmpty(user.getPhone())) {
            MconfigExt mconfigExt = mconfigExtService.selectById(mpid);

            String sms = String.format("充值提醒：亲爱的用户您好，您于%s通过小程序会员充值%s元，充值后余额%s元。",
                    DateUtil.toDateString(order.getCreatetime(), "yyyy年MM月dd日 hh:mm:ss"), order.getRealpay().toString(), account.getTotal().toString());
            String[] params = {DateUtil.toDateString(order.getCreatetime(), "yyyy年MM月dd日 hh:mm:ss"), order.getRealpay().toString(), account.getTotal().toString()};

            Maccount maccount = maccountService.selectOne(new EntityWrapper<Maccount>().eq("mid", mid));
            if (maccount.getSmsmoutTotal() != null && maccount.getSmstotal() > 0 && mconfigExt.getSmstplidcz() != null) {
                smslogService.sendOnetplsms(user.getPhone(), sms, params, mconfigExt.getSmstplidcz(), mid, mpid, order.getSid(), order.getId());
            }
        }

        logger.debug("--------------------------------------af.getOrigin() =" + af.getOrigin());
        if (af != null && af.getOrigin() != null) {
            Czfan czfan = czfanService.selectById(af.getOrigin());
            logger.debug("--------------------------------------czfan =" + czfan);
            //处理充值返券，券再支付成功确认后，才分配到用户账户
            if (czfan != null && czfan.getFanquan() != null && czfan.getFanquan() > 0 && czfan.getQuanshu() > 0) {
                CouponTpl ctpl = couponTplService.selectById(czfan.getFanquan());
                logger.debug("--------------------------------------ctpl =" + ctpl);

                for (int i = 0; i < czfan.getQuanshu(); i++) {
                    if (ctpl == null) {
                        logger.error("======couponTpl is null for id=" + czfan.getFanquan());
                        break;
                    }
                    Coupon coupon = new Coupon();
                    coupon.setIsUnused(1);//未使用
                    coupon.setIsUsed(0);//已使用
                    coupon.setIsForever(ctpl.getIsForever());//永久有效
                    coupon.setIsOutdate(0);//已过期
                    coupon.setState(1);

                    coupon.setMid(af.getMid());
                    coupon.setMpid(af.getMpid());
                    coupon.setUid(af.getUid());
                    coupon.setSid(ctpl.getSid());
                    coupon.setCreatetime(new Date());

                    coupon.setTplid(ctpl.getId());
                    coupon.setType(ctpl.getType());
                    coupon.setName(ctpl.getName());
                    coupon.setSlogo(ctpl.getSlogo());
                    coupon.setSname(ctpl.getSname());
                    coupon.setRemark(ctpl.getRemark());

                    coupon.setCno(StringUtil.getQuanCode(af.getMid()));
                    coupon.setSn(af.getSn());

                    coupon.setStarttime(ctpl.getValidType() == 1 ? DateUtil.getToday() : ctpl.getStarttime());
                    coupon.setEndtime(ctpl.getIsForever() == 1 ? null : ctpl.getValidType() == 1 ? DateUtil.addToday(ctpl.getExpire()) : ctpl.getEndtime());
                    coupon.setCost(ctpl.getCost());
                    coupon.setUsemin(ctpl.getUsemin());
                    coupon.setOriginType(Qgettype.chongzhi.getVal());//领券来源@1：领取；2：分享；3：赠送;4：充值&

                    coupon.insert();
                }
                logger.debug("--------------------------------------czfan.getQuanshu() =" + czfan.getQuanshu());

                if (ctpl != null) {
                    ctpl.setUse(ctpl.getUse() + czfan.getQuanshu());
                    ctpl.updateById();
                }
            }

            if (czfan != null && czfan.getLevel() != null && czfan.getLevel() > 0) {
                Fenxiao fenxiao = fenxiaoService.selectOne(new EntityWrapper<Fenxiao>().eq("mpid", af.getMpid()));
                User ouser = userService.selectById(af.getUid());
                //充值级别小于当前级别 不处理
                if (czfan.getLevel() < ouser.getMemberLevel() || ouser == null) return;

                User nuser = new User();
                nuser.setId(af.getUid());
                nuser.setMemberLevel(czfan.getLevel());
                if (fenxiao != null) nuser.setDiscount(czfan.getLevel() == 1 ? fenxiao.getMzhekou1() :
                        czfan.getLevel() == 2 ? fenxiao.getMzhekou2() :
                                czfan.getLevel() == 3 ? fenxiao.getMzhekou3() :
                                        czfan.getLevel() == 4 ? fenxiao.getMzhekou4() :
                                                czfan.getLevel() == 5 ? fenxiao.getMzhekou5() :
                                                        czfan.getLevel() == 6 ? fenxiao.getMzhekou6() :
                                                                czfan.getLevel() == 7 ? fenxiao.getMzhekou7() : new BigDecimal(100));

                nuser.setDiscount(nuser.getDiscount().divide(new BigDecimal(100)));

                //充值过来的 都是会员或者代理
                nuser.setUtype(czfan.getHytype());
                nuser.setIsMember(1);
                nuser.setIsEcashCard(1);
                nuser.setModifytime(new Date());
                if (czfan.getExpire() != null && czfan.getExpire() > 0) {
                    if (user.getStarttime() == null) nuser.setStarttime(new Date());
                    if (user.getEndtime() == null) nuser.setEndtime(DateUtil.addDay(new Date(), czfan.getExpire()));
                    else nuser.setEndtime(DateUtil.addDay(user.getEndtime(), czfan.getExpire()));
                }
                nuser.setDiscount(new BigDecimal(czfan.getDiscount() / 100));
                nuser.updateById();

                redisService.delUser(nuser.getId());
            }
        }
    }


    private Order jshuifei(int level, Order order, FenxiaoFan fxfan, BigDecimal jiandian) {
        //计算分销额
        if (level == 1) {
            order.setFxe1(order.getRealpay().multiply(fxfan.getFan1()).divide(new BigDecimal(100)));
            if (fxfan.getIsJiandian() == 1) order.setFxe1(order.getFxe1().add(jiandian));
        } else if (level == 2) {
            order.setFxe2(fxfan.getFan2());

            if (fxfan.getIsJiandian() == 1) order.setFxe2(order.getFxe2().add(jiandian));

        } else if (level == 3) {
            order.setFxe3(fxfan.getFan3());

            if (fxfan.getIsJiandian() == 1) order.setFxe3(order.getFxe3().add(jiandian));

        } else if (level == 4) {
            order.setFxe4(fxfan.getFan4());

            if (fxfan.getIsJiandian() == 1) order.setFxe4(order.getFxe4().add(jiandian));

        } else if (level == 5) {
            order.setFxe5(fxfan.getFan5());

            if (fxfan.getIsJiandian() == 1) order.setFxe5(order.getFxe5().add(jiandian));

        } else if (level == 6) {
            order.setFxe6(fxfan.getFan6());

            if (fxfan.getIsJiandian() == 1) order.setFxe6(order.getFxe6().add(jiandian));

        } else if (level == 7) {
            order.setFxe7(fxfan.getFan7());

            if (fxfan.getIsJiandian() == 1) order.setFxe7(order.getFxe7().add(jiandian));
        }
        return order;
    }

    //扫码核销或者确认订单时触发
    //处理商品直接推荐返利
    //先进入待入账佣金，再发放（后发放）
    //奖励的其他类型佣金不在进行第二次发放
    public void shareFanPay(String oid) {

        logger.info("----------------------------------------------shareFanPay come");
        if (Strings.isNullOrEmpty(oid)) {
            return;
        }
        Order order = orderService.selectById(oid);
        Long uid = order.getUid();
        Long mid = order.getMid();
        Long mpid = order.getMpid();
        String sn = order.getOrderNo();

        AccountFlow af = accountFlowService.selectOne(new EntityWrapper<AccountFlow>()
                .eq("sn", sn)
                .eq("xftype", XftypeEnum.sharefan.getVal())
        );
        logger.info("----------------------------------------------shareFanPay af=" + af);

        Boolean flag = false;
        if (af != null) {
            uid = af.getUid();
            MerchantConfig mconfig = redisService.getMconfig(order.getMpid());
            User user = userService.selectById(uid);
            Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
            MerchantApp mapp = redisService.getMApp(mpid);
            boolean autofan = mconfig.getIsAutofan() == 1 || order.getGtype().intValue() == 2;
            logger.info("----------------------------------------------shareFanPay autofan=" + autofan);

            if (autofan) {
                Map<String, String> paymap = qnpay.payPakect(mpid, mapp.getAppid(), user, af.getAmount(), XftypeEnum.sharefan.getName(), "127.0.0.1");
                //如果秒退失败，该佣金自动到用户账户
                logger.info("----------------------------------------------shareFanPay paymap=" + JSON.toJSONString(paymap));
                if (paymap.containsKey("result_code") && paymap.get("result_code").toString().equals("FAIL")) {
                    flag = false;
                } else if (paymap.containsKey("result_code") && paymap.get("result_code").toString().equals("SUCCESS")) {
                    //发放佣金自动到用户账户成功
                    //平台账户记账
                    addMaccountFlow(user, af.getAmount(), sn, IotypeEnum.output, XftypeEnum.withdraw, paymap.get("payment_no"));

                    //用户账户记录提现记录
                    af.setId(null);
                    af.setIotype(IotypeEnum.output.getVal());//个人账户出账
                    af.setXftype(XftypeEnum.withdraw.getVal());//待入账佣金秒到提现

                    af.setState(1);
                    af.setIsConfirm(-1);
                    af.setCreatetime(new Date());
                    af.setRemark("佣金提现至微信账户");
                    af.setTransactionid(paymap.get("payment_no"));
                    af.setLasttotal(act.getTotal());
                    af.setLastamount(act.getAmount());
                    af.insert();

                    Account naccount = new Account();
                    while (!flag) {
                        Account account = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
                        if (account == null) {
                            account = accountService.initAccount(uid, mid, mpid);
                        }

                        Long version = account.getVersion();

                        BigDecimal total = account.getTotal();
                        BigDecimal fanliing = account.getFanliing();
                        BigDecimal fanli = account.getFanli();
                        BigDecimal unuseAmount = account.getUnuseAmount();

                        naccount.setTotal(total.subtract(af.getAmount()));
                        naccount.setUnuseAmount(unuseAmount.subtract(af.getAmount()));
                        //===待处理
                        //佣金只进不出，在结算确认时进入
                        naccount.setFanliing(fanliing.subtract(af.getAmount()));

                        naccount.setModifytime(new Date());
                        naccount.setModifier(uid);
                        naccount.setVersion(version + 1);

                        flag = accountService.update(naccount, new EntityWrapper<Account>().eq("uid", uid).eq("version", version));
                        if (flag) {
                            af.setIsConfirm(1);
                            af.setRuzhang(0);
                            af.setConfirmDate(new Date());
                            af.setLasttotal(account.getTotal());
                            af.setLastamount(account.getAmount());
                            af.updateById();
                        }
                    }
                }
            }
            if (!flag) {
                logger.error("------------------------shareFanPay oid=" + oid);
            }
//            //如果秒退失败，该佣金自动到用户账户
//            Account naccount = new Account();
//            if (!flag) {
//                af.setId(null);
//                af.setIotype(IotypeEnum.input.getVal());//个人账户出账
//                af.setXftype(XftypeEnum.ruzhang.getVal());//待入账佣金秒到提现
//                af.setXftypename(XftypeEnum.ruzhang.getName());//待入账佣金秒到提现
//                af.setRemark(XftypeEnum.ruzhang.getName());
//                af.setState(1);
//                af.setIsConfirm(-1);
//                af.setCreatetime(new Date());
//
//                af.insert();
//            }
//
//            while (!flag) {
//                Account account = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
//                if (account == null) {
//                    break;
//                }
//                Long version = account.getVersion();
//
//                BigDecimal fanli = account.getFanli();
//                BigDecimal amount = account.getAmount();
//                BigDecimal fanliing = account.getFanliing();
//                BigDecimal unuseAmount = account.getUnuseAmount();
//
//                naccount.setAmount(amount.add(af.getAmount()));
//                //佣金只进不出，在结算确认时进入
//                naccount.setFanliing(fanliing.subtract(af.getAmount()));
//                naccount.setFanli(fanli.add(af.getAmount()));
//
//                naccount.setUnuseAmount(unuseAmount.subtract(af.getAmount()));
//
//                naccount.setModifytime(new Date());
//                naccount.setModifier(uid);
//                naccount.setVersion(version + 1);
//
//                flag = accountService.update(naccount, new EntityWrapper<Account>().eq("uid", uid).eq("version", version));
//                if (flag) {
//                    af.setConfirmDate(new Date());
//                    af.setIsConfirm(1);
//                    af.setRuzhang(1);
//                    af.setLasttotal(account.getTotal());
//                    af.updateById();
//                }
//            }
        }

        //更新商品分销奖励数
        logger.info("---------------------------------------------------update setFxjiangshu for hexiao at gid=" + order.getGid());
        Goods goods = goodsService.selectById(order.getGid());
        Goods ngoods = new Goods();
        ngoods.setId(order.getGid());
        ngoods.setFxjiangshu(goods.getFxjiangshu() == null ? 1 : goods.getFxjiangshu() + 1);
        ngoods.setModifytime(new Date());
        ngoods.updateById();
        logger.info("---------------------------------------------------update setFxjiangshu for hexiao at gid=" + order.getGid());

        //order 返币 返积分 返券
        boolean nowfan = order.getFantimeType().intValue() == FantimeType.hexiao.getVal();
        User user = userService.selectById(order.getFanuid());

        if (order.getShareBonusType().intValue() == XffanType.quan.getVal()) {//返券
            //待完善

        } else if (order.getShareBonusType().intValue() == XffanType.xnbi.getVal() && nowfan) {
            //返币
            addXnbiFlow(user, order.getSharefan(), true, FantimeType.hexiao.getVal(), order.getOrderNo(), IotypeEnum.input, XftypeEnum.sharefan, XftypeEnum.sharefan.getName());

        } else if (order.getShareBonusType().intValue() == XffanType.jifen.getVal() && nowfan) {
            //返积分
            addJifenFlow(user, order.getSharefan(), true, FantimeType.hexiao.getVal(), order.getOrderNo(), IotypeEnum.input, JftypeEnum.share, JftypeEnum.share.getName());
        }
    }

    //群转发
    //非支付时触发
    //奖励的其他类型佣金不在进行第二次方法
    //群发奖励不支持退款
    public void qunzhuanfaPay(String shareid) {

        logger.info("-----------------------------------------------qunzhuanfaPay come");
        Share share = shareService.selectById(shareid);
        logger.debug("----------------------------------------------share=" + share);
        if (share == null) return;

        //返现用户
        Long mpid = share.getMpid();
        Long uid = share.getUid();
        Long ywid = share.getYwid();

        logger.debug("-----------------qunzhuanfaPay mpid=" + mpid);
        logger.debug("-----------------qunzhuanfaPay uid=" + uid);
        logger.debug("-----------------qunzhuanfaPay ywid=" + ywid);
        if (ywid == null) return;

        GoodsQunzf goodsQunzf = goodsQunzfService.selectById(ywid);
        logger.debug("-----------------qunzhuanfaPay goodsQunzf=" + goodsQunzf);
        if (goodsQunzf == null) return;

        User user = userService.selectById(uid);
        if (user == null) return;

        //规则1：一个商品对一个人一个群只有一次奖励【系统默认】
        //规则2：一个人一个活动一天只限制群发奖励一次
        //规则3：同一个活动同一个人限制群发奖励次数
        //规则4： 群发奖励超过份数，则不再发群发红包
        Integer todaycout = shareService.selectCount(new EntityWrapper<Share>()
                .eq("sendoff", 1)
                .eq("uid", share.getUid())
                .eq("ywid", share.getYwid())
                .eq("sentdate", DateUtil.getToday()));
        logger.debug("---------------------------------------qunzhuanfaPay and todaycout=" + todaycout);
        if (todaycout > 0) return;

        //【同一个活动同一个人限制群发奖励次数】
        Integer hdcout = shareService.selectCount(new EntityWrapper<Share>()
                .eq("ywid", share.getYwid())
                .eq("sendoff", 1)
                .eq("uid", share.getUid()));
        logger.debug("---------------------------------------qunzhuanfaPay and hdcout=" + hdcout);
        if (hdcout >= goodsQunzf.getOneptimes()) return;

        Integer sendoffcout = shareService.selectCount(new EntityWrapper<Share>()
                .eq("ywid", share.getYwid())
                .eq("sendoff", 1));
        logger.debug("-----------------qunzhuanfaPay sendoffcout=" + sendoffcout);
        logger.debug("-----------------goodsQunzf.jiang_fenshu=" + goodsQunzf.getJiangFenshu());

        //群发奖励超过份数，则不再发群发红包
        if (goodsQunzf.getJiangFenshu() != null && goodsQunzf.getJiangFenshu() > 0
                && sendoffcout >= goodsQunzf.getJiangFenshu()) {
            return;
        }

        //计算佣金随机
        BigDecimal money = RandSplitNumUtils.genRandPack(goodsQunzf.getJiangMount().intValue());
        if (money.doubleValue() > goodsQunzf.getJiangMount().doubleValue()) money = goodsQunzf.getJiangMount();
        if (goodsQunzf.getJiangType().intValue() != XffanType.qian.getVal()) {
            money = new BigDecimal(money.intValue());
        }

        //群发奖励直接奖励，自动奖励
        //否则先放入待返利中。。。
        String sn = StringUtil.getSnNo("QTYJ");
        Order order = new Order();
        order.setOrderNo(sn);
        if (goodsQunzf.getJiangType() == XffanType.jifen.getVal())
            jffanyong(user, money, XffanType.jifen.getVal(), sn, true, JftypeEnum.share);
        if (goodsQunzf.getJiangType() == XffanType.qian.getVal())
            fanyong(user, money, XffanType.qian.getVal(), FantimeType.now.getVal(), order, true, true, XftypeEnum.autofanli);
        if (goodsQunzf.getJiangType() == XffanType.xnbi.getVal())
            fanyong(user, money, XffanType.xnbi.getVal(), FantimeType.now.getVal(), order, true, true, XftypeEnum.autofanli);

        share.setModifytime(new Date());
        share.setModifier(uid);
        share.setSendoff(1);
        share.setSentdate(DateUtil.getToday());
        share.updateById();

        logger.info("----------------------------qunzhuanfaPay over");
    }

    //处理商品+活动订单直接推荐返利
    //该商品是非买单充值商品gtype>0
    //直推佣金先按照总订单，不分开计算
    //直推佣金计算=必须order.getSharefan()>0
    public void shareFan(Order order) {

        logger.info("----------------------------shareFan come");

        //返现用户
        Long mid = order.getMid();
        Long mpid = order.getMpid();
        Long uid = order.getUid();
        Long gid = order.getGid();
        Long fanuid = order.getFanuid();
        logger.debug("---------------------------shareFan for fanuid=" + fanuid);
        logger.debug("---------------------------shareFan for order.getSharefan()=" + order.getSharefan());
        if (order.getSharefan() == null || order.getSharefan().doubleValue() <= 0) {
            return;
        }

        //此方法只计算gid>0,买单充值不在该逻辑
        if (order.getGid() == null) {
            logger.info("--------------------------------------shareFan return order.getGid()==null");
            return;
        }
        //--------1、获取佣金人优先级从（推荐人+推荐商品）第一
        //--------2、获取佣金人优先级从转发记录
        if (fanuid == null) {
            //最新的一次推荐链接
            List<ShareOpen> shareOpens = shareOpenService.selectList(new EntityWrapper<ShareOpen>()
                    .eq("mpid", order.getMpid())
                    .eq("ywid", gid)
                    .eq("uid", uid)
                    .orderBy("id", false)
            );
            if (shareOpens != null && shareOpens.size() > 0) {
                ShareOpen shareOpen = shareOpens.get(0);
                if (shareOpen.getZuid() != null) fanuid = shareOpen.getZuid();
                else {
                    User user = redisService.getUserByGuid(shareOpen.getZguid());
                    fanuid = user == null ? null : user.getId();
                }
            }
        }

        logger.info("-------------------------------------------------------shareFan fanuid=" + fanuid);
        if (fanuid == null) {
            return;
        }

        //秒到+非秒到账
        BigDecimal fxe = order.getSharefan();
        User fxuser = userService.selectById(fanuid);

        Goods goods = goodsService.selectById(order.getGid());
        int paytime = FantimeType.payok.getVal();
        //mconfig.getIsMiaotui() 该属性针对现金返佣来说
        //mconfig.getIsAutofan() 该属性针对现金返佣来说
        //直接入账触发点 1：支付成功后；2：确认收货|扫码核销后；3：确认后7天到账&
        //==待实现 3：确认后7天到账&
        //否则先放入待返利中。。。
        boolean nowfan = order.getFantimeType().intValue() == FantimeType.payok.getVal();

        logger.info("------------------------------------------------------shareFan nowfan=" + nowfan);
        // 返佣需要入账做记录
        fanyong(fxuser, fxe, goods.getShareBonusType(), paytime, order, true, nowfan, XftypeEnum.sharefan);

        logger.info("-----------------------------------shareFan over");
    }

    //核销之后自购返处理逻辑
    public void zigouFan(String id, String fantimeType) {
        logger.info("-----------------------------------------------------zigouFan with fantimeType come");
        Order order = orderService.selectById(id);
        if (order == null) {
            logger.info("------------------------zigouFan with fantimeType order is null for oid=" + id);
            return;
        }

        Long uid = order.getUid();
        User user = userService.selectById(uid);
        if (user == null) {
            logger.info("------------------------zigouFan with fantimeType user is null for uid=" + uid);
            return;
        }
        Goods goods = goodsService.selectById(order.getGid());
        MerchantConfig mconfig = redisService.getMconfig(order.getMpid());
        if (mconfig.getFantimeType().intValue() == FantimeType.payok.getVal()) return;//zigouFan(Order order) method已处理

        //处理自购奖励返券
        if (goods != null && goods.getZgfanType() != null && order.getFantimeType() != null
                && order.getFantimeType().intValue() == FantimeType.payok.getVal()) {
            //处理自购返券
            if (goods.getZgfanType() != null &&
                    goods.getZgfanType().intValue() == XffanType.quan.getVal()) zigouFanquan(order);
        }
        int fantime = Integer.parseInt(fantimeType);
        zigouFan(order, fantime, fantime == order.getFantimeType());
    }

    //支付之后自购返处理逻辑
    public void zigouFan(Order order, Integer fantimeType, Boolean ruzhang) {

        logger.info("------------------------------------------------------zigouFan come");
        //返现用户
        Long mpid = order.getMpid();
        Long uid = order.getUid();
        logger.info("-----------------zigouFan mpid=" + mpid);

        User user = userService.selectById(uid);
        if (user == null) {
            logger.info("------------------------zigouFan user is null for uid=" + uid);
            return;
        }

        //秒到+非秒到账
        BigDecimal bi = order.getFanbi();
        BigDecimal jifen = order.getFanjifen();
        BigDecimal qian = order.getFanqian();

        logger.info("--------------------------------------zigouFan start jifen=" + jifen);
        logger.info("--------------------------------------zigouFan start qian=" + qian);
        logger.info("--------------------------------------zigouFan start bi=" + bi);

        MerchantConfig mconfig = redisService.getMconfig(mpid);

        //mconfig.getIsMiaotui() 该属性针对现金返佣来说
        //mconfig.getIsAutofan() 该属性针对现金返佣来说
        //直接入账触发点 1：支付成功后；2：确认收货|扫码核销后；3：确认后7天到账&
        //否则先放入待返利中。。。
        boolean nowfan = mconfig.getIsAutofan() == 1 && ruzhang;

        if (jifen != null && jifen.doubleValue() > 0)
            jffanyong(user, jifen, XffanType.jifen.getVal(), order.getOrderNo(), ruzhang, JftypeEnum.xffanli);
        if (qian != null && qian.doubleValue() > 0)
            fanyong(user, qian, XffanType.qian.getVal(), fantimeType, order, ruzhang, nowfan, XftypeEnum.xffanli);
        if (bi != null && bi.doubleValue() > 0)
            fanyong(user, bi, XffanType.xnbi.getVal(), fantimeType, order, ruzhang, nowfan, XftypeEnum.xffanli);

        logger.info("------------------------------------------------zigouFan over");
    }

    public void zigouFanquan(Order order) {

        logger.info("------------------------------------------------------zigouFanquan come");

        //返现用户
        Long mpid = order.getMpid();
        logger.info("======zigouFan mpid=" + mpid);

        List<OrderGoods> oglist = orderGoodsService.selectList(new EntityWrapper<OrderGoods>()
                .setSqlSelect("oid,gid")
                .eq("oid", order.getId()));
        List<String> gidlist = new ArrayList<String>();
        for (OrderGoods item : oglist) {
            if (item.getGid() != null) gidlist.add(item.getGid().toString());
        }

        if (gidlist.size() == 0) {
            logger.info("-----------------------------------------------gidlist.size()==0");
            return;
        }
        List<Goods> goodslist = goodsService.selectBatchIds(gidlist);
        for (Goods item : goodslist) {
            logger.info("-------------------------------------------------zigouFanquan Goods item=" + JSON.toJSONString(item));

            if (item.getZgfanType() != null && item.getZgfanType().intValue() == 3 && item.getZgfanYwid() != null) {
                int num = item.getZgfanMount();
                Long tplid = item.getZgfanYwid();
                CouponTpl ctpl = couponTplService.selectById(tplid);
                for (int i = 0; i < num; i++) {
                    Coupon coupon = new Coupon();
                    coupon.setIsUnused(1);//未使用
                    coupon.setIsUsed(0);//已使用
                    coupon.setIsForever(ctpl.getIsForever());//永久有效
                    coupon.setIsOutdate(0);//已过期
                    coupon.setState(1);

                    coupon.setMid(order.getMid());
                    coupon.setMpid(order.getMpid());
                    coupon.setUid(order.getUid());
                    coupon.setSid(ctpl.getSid());
                    coupon.setCreatetime(new Date());

                    coupon.setTplid(ctpl.getId());
                    coupon.setType(ctpl.getType());
                    coupon.setName(ctpl.getName());
                    coupon.setSlogo(ctpl.getSlogo());
                    coupon.setSname(ctpl.getSname());
                    coupon.setRemark(ctpl.getRemark());

                    coupon.setCno(StringUtil.getQuanCode(order.getMid()));
                    coupon.setSn(order.getOrderNo());

                    coupon.setStarttime(ctpl.getValidType() == 1 ? DateUtil.getToday() : ctpl.getStarttime());
                    coupon.setEndtime(ctpl.getIsForever() == 1 ? null : ctpl.getValidType() == 1 ? DateUtil.addToday(ctpl.getExpire()) : ctpl.getEndtime());
                    coupon.setCost(ctpl.getCost());
                    coupon.setUsemin(ctpl.getUsemin());
                    coupon.setOriginType(Qgettype.chongzhi.getVal());//领券来源@1：领取；2：分享；3：赠送;4：充值&

                    coupon.insert();
                }

                CouponTpl ctpl2 = new CouponTpl();
                ctpl2.setUse(ctpl.getUse() + num);
                ctpl2.setId(ctpl.getId());
                ctpl2.updateById();
            }
        }

        logger.info("======zigouFanquan over");
    }

    public void shengjiCheck(String uid, String type, String ywid) {
        logger.info("-----------------------------------start to shengjiCheck uid=" + uid);
        logger.info("-----------------------------------start to shengjiCheck type=" + type);
        logger.info("-----------------------------------start to shengjiCheck ywid=" + ywid);

        Account account = accountService.selectOne(new EntityWrapper<Account>()
                .setSqlSelect("uid,ljxiaofei,charge_amount chargeAmount")
                .eq("uid", uid));
        User user = userService.selectById(uid);
        Long mpid = user.getMpid();

        logger.debug("===shengjiCheck user=" + user);
        int mlevel = user.getMemberLevel();
        int oldlevel = mlevel;
        BigDecimal zhekou = new BigDecimal(1);
        Fenxiao fenxiao = fenxiaoService.selectOne(new EntityWrapper<Fenxiao>().eq("mpid", mpid));
        if (fenxiao == null) {
            logger.info("=====fenxiao not exist for mpid=" + mpid);
            return;
        }

        if (fenxiao.getHuiyuantype() == Huiyuantype.charge.getVal() && !Strings.isNullOrEmpty(ywid)
                && !Strings.isNullOrEmpty(type) && type.equals("recharge")) {
            Czfan czfan = czfanService.selectById(ywid);
            if (czfan == null) {
                return;
            }
            mlevel = czfan.getLevel();
        } else if (fenxiao.getHuiyuantype() == Huiyuantype.hygoods.getVal() && !Strings.isNullOrEmpty(ywid)
                && !Strings.isNullOrEmpty(type) && type.equals("hygoods")) {

            Goods hygoods = goodsService.selectById(ywid);
            mlevel = hygoods != null && hygoods.getMlevel() != null ? hygoods.getMlevel() : 0;
            logger.info("-----------------------------------------------start to check huiyuan mlevel=" + mlevel);

            if (mlevel < 0 || fenxiao == null || mlevel > fenxiao.getFxlevel()) {
                logger.error("-----------------------------------------------fenxiao.getHuiyuantype()==Huiyuantype.hygoods.getVal() mlevel=" + mlevel);
                return;
            }
        } else if (fenxiao.getHuiyuantype() == Huiyuantype.xiaofei.getVal()) {

            if (account.getLjxiaofei() == null) {
                logger.error("-----------------------------------------------fenxiao.getHuiyuantype()==Huiyuantype.hygoods.getVal() mlevel=" + mlevel);
                return;
            }

            if (fenxiao.getHuifei7() != null && account.getLjxiaofei().doubleValue() >= fenxiao.getHuifei7().doubleValue()) {
                mlevel = 7;
            } else if (fenxiao.getHuifei6() != null && account.getLjxiaofei().doubleValue() >= fenxiao.getHuifei6().doubleValue()) {
                mlevel = 6;
            } else if (fenxiao.getHuifei5() != null && account.getLjxiaofei().doubleValue() >= fenxiao.getHuifei5().doubleValue()) {
                mlevel = 5;
            } else if (fenxiao.getHuifei4() != null && account.getLjxiaofei().doubleValue() >= fenxiao.getHuifei4().doubleValue()) {
                mlevel = 4;
            } else if (fenxiao.getHuifei3() != null && account.getLjxiaofei().doubleValue() >= fenxiao.getHuifei3().doubleValue()) {
                mlevel = 3;
            } else if (fenxiao.getHuifei2() != null && account.getLjxiaofei().doubleValue() >= fenxiao.getHuifei2().doubleValue()) {
                mlevel = 2;
            } else if (fenxiao.getHuifei1() != null && account.getLjxiaofei().doubleValue() >= fenxiao.getHuifei1().doubleValue()) {
                mlevel = 1;
            }

        } else if (fenxiao.getHuiyuantype() == Huiyuantype.xianxia.getVal()) {
            //===待完善，表单提交控制,同步更新会员级别
        }

        //更新粉丝状态
        MerchantConfig mconfig = redisService.getMconfig(mpid);
        if (mconfig.getIsSuofen() == 1) {
            //Fens fens=  fensService.selectOne(new EntityWrapper<Fens>().setSqlSelect("id,status").eq("uid",uid));
            Fens fens = new Fens();
            fens.setStatus(2);
            fensService.update(fens, new EntityWrapper<Fens>().setSqlSelect("id,status").eq("uid", uid));
        } else {
            //====待完善，非锁粉模式下
        }

        if (mlevel <= oldlevel) {
            logger.info("------------------------------------mlevel<=oldlevel return and mlevel=" + mlevel + " oldlevel=" + oldlevel);
            return;
        }

        zhekou = mlevel == 1 ? fenxiao.getMzhekou1() :
                mlevel == 2 ? fenxiao.getMzhekou2() :
                        mlevel == 3 ? fenxiao.getMzhekou3() :
                                mlevel == 4 ? fenxiao.getMzhekou4() :
                                        mlevel == 5 ? fenxiao.getMzhekou5() :
                                                mlevel == 6 ? fenxiao.getMzhekou6() :
                                                        mlevel == 7 ? fenxiao.getMzhekou7() : new BigDecimal(100);

        //自动升级会员级别
        //===待处理
        User nuser = new User();
        nuser.setId(user.getId());
        nuser.setMemberLevel(mlevel);//自动升级会员级别
        if (zhekou != null) nuser.setDiscount(zhekou.divide(new BigDecimal(100)));//会员折扣
        nuser.setIsMember(1);        //自动升级会员级别
        nuser.updateById();

        //清楚缓存
        redisService.delUser(user.getId());

    }

    //大礼包拆分到自己名下
    //优惠券大礼包，优惠券放在自己名下
    private void orderDalibao(String oid, String gid, String uid) {

        logger.info("=========================================================orderDalibao is coming");
        Goods goods = goodsService.selectById(gid);
        Order order = orderService.selectOne(new EntityWrapper<Order>().setSqlSelect("id,order_no orderNo,uid").eq("id", oid));
        if (Strings.isNullOrEmpty(goods.getQuans())) {
            logger.info("===================orderDalibao goods.getQuans() is null");
            return;
        }

        List<String> ids = Arrays.asList(goods.getQuans().split(";"));
        List<CouponTpl> couponTpls = couponTplService.selectBatchIds(ids);

        for (CouponTpl ctpl : couponTpls) {
            Coupon coupon = new Coupon();
            coupon.setIsUnused(1);//未使用
            coupon.setIsUsed(0);//已使用
            coupon.setIsForever(ctpl.getIsForever());//永久有效
            coupon.setIsOutdate(0);//已过期
            coupon.setState(1);

            coupon.setMid(goods.getMid());
            coupon.setMpid(goods.getMpid());
            coupon.setUid(Long.parseLong(uid));
            coupon.setSid(ctpl.getSid());
            coupon.setOid(Long.valueOf(oid));
            coupon.setCreatetime(new Date());

            coupon.setTplid(ctpl.getId());
            coupon.setType(ctpl.getType());
            coupon.setName(ctpl.getName());
            coupon.setSname(ctpl.getSname());
            coupon.setSlogo(ctpl.getSlogo());
            coupon.setRemark(ctpl.getRemark());

            coupon.setCno(StringUtil.getQuanCode(goods.getMpid()));
            coupon.setSn(order.getOrderNo());

            coupon.setStarttime(ctpl.getValidType() == 1 ? DateUtil.getToday() : ctpl.getStarttime());
            coupon.setEndtime(ctpl.getIsForever() == 1 ? null : ctpl.getValidType() == 1 ? DateUtil.addToday(ctpl.getExpire()) : ctpl.getEndtime());
            coupon.setCost(ctpl.getCost());
            coupon.setUsemin(ctpl.getUsemin());
            coupon.setOriginType(Qgettype.buy.getVal());//领券来源@1：领取；2：分享；3：赠送;4：充值;5:购买&
            coupon.insert();

            ctpl.setUse(ctpl.getUse() + 1);
            ctpl.insertOrUpdate();
        }
    }

    //返佣金入账（都是首次）
    //返币 返积分 返优惠券 没有待入账一说
    private void fanyong(User user, BigDecimal fxe, Integer fantype, Integer fantime, Order order, Boolean ruzhang, Boolean nowfan, XftypeEnum xftypeEnum) {

        Map<String, Object> paymap = new HashMap<String, Object>();
        MerchantApp mapp = redisService.getMApp(user.getMpid());
        if (fantype == XffanType.qian.getVal()) {
            //现金很特殊，区分不同时刻返佣金，先入账
            //商家出账记录，对于商家发生实际现金变动时，才会生成记录
            addAccountFlow(user, fxe, ruzhang, fantime, order, IotypeEnum.input, xftypeEnum);
            if (nowfan) {
                paymap = qnpay.payPakect(user.getMpid(), mapp.getAppid(), user, fxe, "佣金奖励", "127.0.0.1");
                if (paymap.containsKey("result_code") && paymap.get("result_code").toString().equals("SUCCESS")) {
                    //秒到账成功
                    addMaccountFlow(user, fxe, order.getOrderNo(), IotypeEnum.output, xftypeEnum, order.getTransactionId());
                    //奖励佣金直接发放
                    addAccountAutoFanFlow(user, fxe, fantime, order, IotypeEnum.output, xftypeEnum.autofanli, paymap.get("payment_no").toString());
                }
            }
        } else if (fantype == XffanType.quan.getVal() && nowfan) {//返券
            //待完善

        } else if (fantype == XffanType.xnbi.getVal() && nowfan) {//返币
            addXnbiFlow(user, fxe, ruzhang, fantime, order.getOrderNo(), IotypeEnum.input, xftypeEnum, xftypeEnum.getName());
        } else if (fantype == XffanType.jifen.getVal() && nowfan) {
            //返积分
            addJifenFlow(user, fxe, ruzhang, fantime, order.getOrderNo(), IotypeEnum.input, JftypeEnum.share, xftypeEnum.getName());
        }
    }

    //返佣金入账（都是首次）
    private void mchfanyong(User user, BigDecimal fxe, Integer fantype, Integer fantime, Order order, Boolean ruzhang,
                            Boolean autofan, XftypeEnum xftypeEnum, SaccountFlow saccountFlow) {

        Map<String, Object> paymap = new HashMap<String, Object>();
        MerchantApp mapp = redisService.getMApp(user.getMpid());
        if (fantype == XffanType.qian.getVal()) {
            //现金很特殊，区分不同时刻返佣金，先入账
            //商家出账记录，对于商家发生实际现金变动时，才会生成记录
            addAccountFlow(user, fxe, ruzhang, fantime, order, IotypeEnum.input, xftypeEnum);
            if (autofan) {
                paymap = qnpay.payPakect(user.getMpid(), mapp.getAppid(), user, fxe, "佣金奖励", "127.0.0.1");
                if (paymap.containsKey("result_code") && paymap.get("result_code").toString().equals("SUCCESS")) {
                    //秒到账成功
                    addMaccountFlow(user, fxe, order.getOrderNo(), IotypeEnum.output, xftypeEnum, order.getTransactionId());
                    //奖励佣金直接发放
                    addAccountAutoFanFlow(user, fxe, fantime, order, IotypeEnum.output, xftypeEnum.autofanli, paymap.get("payment_no").toString());
                    //商家账户扣除营销金额
                    saccountFlow.setTransactionid(paymap.get("payment_no").toString());
                    saccountService.addSaccountOutFlow(saccountFlow);
                }
            }
        } else if (fantype == XffanType.quan.getVal()) {//返券
            //待完善

        } else if (fantype == XffanType.xnbi.getVal()) {//返币
            addXnbiFlow(user, fxe, ruzhang, fantime, order.getOrderNo(), IotypeEnum.input, xftypeEnum, xftypeEnum.getName());
        }
    }

    //返积分入账（都是首次）
    private void jffanyong(User user, BigDecimal fxe, Integer fantype, String sn, Boolean ruzhang, JftypeEnum jftypeEnum) {

        MerchantConfig mconfig = redisService.getMconfig(user.getMpid());
        Integer fantime = mconfig.getFantimeType();
        if (fantype == XffanType.jifen.getVal()) {
            //积分入账，除了现金返利都及时入账
            addJifenFlow(user, fxe, ruzhang, fantime, sn, IotypeEnum.input, jftypeEnum, "用户分享返积分结算");
        }
    }

    private void addMaccountFlow(User user, BigDecimal money,
                                 String sn, IotypeEnum iotype, XftypeEnum xftype, String transactionId) {
        Long uid = user.getId();
        Long mid = user.getMid();
        Long mpid = user.getMpid();

        //付款失败，进入待转账流水
        MaccountFlow maf = new MaccountFlow();
        maf.setAmount(money);//实付100剩余20在一次充值时已更新
        maf.setMamount(new BigDecimal(0));//各种抵扣额度=商家的营销费用=总营销金额130

        maf.setUid(uid);
        maf.setMid(mid);
        maf.setMpid(mpid);

        maf.setCreatetime(new Date());
        maf.setTradetime(new Date());
        maf.setState(1);
        maf.setIsConfirm(-1);

        maf.setIotype(iotype.getVal());
        maf.setXftype(xftype.getVal());

        maf.setRemark(xftype.getName());
        maf.setSn(sn);
        maf.setTransactionid(transactionId);
        maf.insert();

        boolean flag = false;

        Maccount maccount = new Maccount();//企业付款成功
        while (!flag) {
            Maccount ma = maccountService.selectOne(new EntityWrapper<Maccount>().eq("mid", mid));
            if (ma == null) {
                ma = maccountService.initMaccount(uid, mid);
            }

            Long version = ma.getVersion();
            BigDecimal amount = ma.getAmount();
            BigDecimal total = ma.getTotal();
            BigDecimal sale = ma.getSaleAmount();
            BigDecimal market = ma.getMamount();

            maccount.setTotal(iotype.getVal() == -1 ? total.subtract(maf.getAmount()) : total.add(maf.getAmount()));       //总金额
            if (iotype.getVal() == 1) maccount.setSaleAmount(sale.add(maf.getAmount()));//累计销售额度
            maccount.setAmount(iotype.getVal() == -1 ? amount.subtract(maf.getAmount()) : amount.add(maf.getAmount()));    //可用余额
            maccount.setMamount(iotype.getVal() == -1 ? market.subtract(maf.getMamount()) : market.add(maf.getMamount()));  //营销总金额

            maccount.setModifytime(new Date());
            maccount.setModifier(uid);
            maccount.setVersion(version + 1);

            maf.setIsConfirm(1);
            maf.setLasttotal(ma.getTotal());
            maf.setConfirmDate(new Date());

            flag = maccountService.update(maccount, new EntityWrapper<Maccount>().eq("id", ma.getId()).eq("version", version));
            if (flag) maf.insertOrUpdate();
            logger.info("===========maccount flag=" + flag);
        }
    }

    //返佣流水,iotype==1
    private void addAccountFlow(User user, BigDecimal money, Boolean ruzhang, Integer fantimeType,
                                Order order, IotypeEnum iotype, XftypeEnum xftype) {
        Long uid = user.getId();
        Long mid = user.getMid();
        Long mpid = user.getMpid();

        //付款失败，进入待转账流水
        AccountFlow af = new AccountFlow();
        af.setAmount(money);
        af.setDikou(new BigDecimal(0));//总营销金额 130
        af.setRealpay(new BigDecimal(0));//总价200 实付100
        af.setTotal(af.getAmount());

        User ruser = userService.selectById(uid);
        af.setNickname(ruser != null ? ruser.getNickName() : null);
        af.setHeadimg(ruser != null ? ruser.getAvatarPic() : null);
        af.setPhone(ruser != null ? ruser.getPhone() : null);

        af.setSn(order.getOrderNo());
        af.setTransactionid(order.getTransactionId());
        af.setIotype(iotype.getVal());//个人账户出账
        af.setXftype(xftype.getVal());//消费类型
        af.setFantimeType(fantimeType);//个人消费

        af.setIsConfirm(-1);
        af.setRuzhang(-1);
        af.setState(1);
        af.setTradetime(new Date());
        af.setCreatetime(new Date());
        af.setRemark(xftype.getName());
        af.setUid(uid);
        af.setMid(mid);
        af.setMpid(mpid);

        af.setSid(order.getSid());
        af.setLeagueid(order.getLeagueid());
        af.insert();

        Boolean flag = false;
        Account naccount = new Account();
        while (!flag) {
            Account account = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
            if (account == null) {
                account = accountService.initAccount(uid, mid, mpid);
            }

            af.setIsConfirm(1);
            af.setLasttotal(account.getTotal());
            af.setLastamount(account.getAmount());
            af.setConfirmDate(new Date());

            Long version = account.getVersion();

            BigDecimal total = account.getTotal();
            BigDecimal amount = account.getAmount();

            BigDecimal unuseAmount = account.getUnuseAmount();
            BigDecimal fanliing = account.getFanliing();

            naccount.setTotal(iotype.getVal() == 1 ? total.add(af.getAmount()) : total.subtract(af.getAmount()));

            if (ruzhang) {
                af.setRuzhang(1);
                naccount.setAmount(iotype.getVal() == 1 ? amount.add(af.getAmount()) : amount.subtract(af.getAmount()));
            } else {
                naccount.setFanliing(iotype.getVal() == 1 ? fanliing.add(af.getAmount()) : fanliing.subtract(af.getAmount()));
                naccount.setUnuseAmount(iotype.getVal() == 1 ? unuseAmount.add(af.getAmount()) : unuseAmount);
            }
            naccount.setModifytime(new Date());
            naccount.setModifier(uid);
            naccount.setVersion(version + 1);

            flag = accountService.update(naccount, new EntityWrapper<Account>().eq("uid", uid).eq("version", version));
            if (flag) af.updateById();
        }
    }

    //自动发放佣金，不走总账户
    //总账户不增加，可用账户不增加，累计佣金增加
    private void addAccountAutoFanFlow(User user, BigDecimal money, Integer fantimeType,
                                       Order order, IotypeEnum iotype, XftypeEnum xftype, String paymentno) {
        Long uid = user.getId();
        Long mid = user.getMid();
        Long mpid = user.getMpid();

        //付款失败，进入待转账流水
        AccountFlow af = new AccountFlow();
        af.setAmount(new BigDecimal(0));
        af.setDikou(new BigDecimal(0));
        af.setRealpay(money);//实际提现
        af.setTotal(money);

        User ruser = userService.selectById(uid);
        af.setNickname(ruser != null ? ruser.getNickName() : null);
        af.setHeadimg(ruser != null ? ruser.getAvatarPic() : null);
        af.setPhone(ruser != null ? ruser.getPhone() : order.getPhone());

        af.setSn(order.getOrderNo());
        af.setTransactionid(paymentno);
        af.setIotype(iotype.getVal());//个人账户出账
        af.setXftype(xftype.getVal());//消费类型
        af.setXftypename(xftype.getName());//消费类型
        af.setFantimeType(fantimeType);//个人消费

        af.setState(1);
        af.setIsConfirm(-1);
        af.setRuzhang(0);
        af.setTradetime(new Date());
        af.setCreatetime(af.getTradetime());
        af.setRemark(xftype.getName());

        af.setUid(uid);
        af.setMid(mid);
        af.setMpid(mpid);
        af.setSid(order.getSid());
        af.setLeagueid(order.getLeagueid());
        af.insert();

        Boolean flag = false;
        Account naccount = new Account();
        while (!flag) {
            Account account = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
            if (account == null) {
                account = accountService.initAccount(uid, mid, mpid);
            }

            Long version = account.getVersion();
            BigDecimal fanli = account.getFanli();

            naccount.setFanli(fanli.add(af.getRealpay()));

            naccount.setModifytime(new Date());
            naccount.setModifier(uid);
            naccount.setVersion(version + 1);

            af.setIsConfirm(1);
            af.setRuzhang(0);//只有延时佣金【需要核销或者需要确认订单的】才有 ruzhang=1
            af.setConfirmDate(new Date());
            af.setLasttotal(account.getTotal());
            af.setLastamount(account.getAmount());
            flag = accountService.update(naccount, new EntityWrapper<Account>().eq("uid", uid).eq("version", version));
            if (flag) af.updateById();
        }
    }

    private void addXnbiFlow(User user, BigDecimal money, Boolean ruzhang, Integer fantimeType,
                             String sn, IotypeEnum iotype, XftypeEnum xftype, String remark) {
        Long uid = user.getId();
        Long mid = user.getMid();
        Long mpid = user.getMpid();

        XnbiFlow xflow = new XnbiFlow();
        xflow.setConfirmDate(new Date());
        xflow.setCreatetime(new Date());
        xflow.setIotype(iotype.getVal());
        xflow.setIsConfirm(1);
        xflow.setJftype(xftype.getVal());
        xflow.setFantimeType(fantimeType);//===待实现

        xflow.setUid(uid);
        xflow.setMid(mid);
        xflow.setMpid(mpid);
        xflow.setRemark(remark);
        xflow.setNum(money);
        xflow.setSn(sn);
        xflow.setState(1);
        logger.debug("======xflow=" + xflow);
        xflow.insert();

        ruzhang = true;//及时入账

        Boolean flag = false;
        while (!flag) {
            Xnbi xbi = xnbiService.selectOne(new EntityWrapper<Xnbi>().eq("uid", uid));
            if (xbi == null) xbi = xnbiService.initXnbi(uid, mid, mpid);
            Long version = xbi.getVersion();
            BigDecimal total = xbi.getTotal();
            BigDecimal fanliing = xbi.getFanliing();

            if (ruzhang) xbi.setTotal(iotype.getVal() == 1 ? total.add(money) : total.subtract(money));
            else xbi.setFanliing(iotype.getVal() == 1 ? fanliing.add(money) : fanliing.subtract(money));

            xbi.setModifytime(new Date());
            xbi.setModifier(uid);
            xbi.setVersion(version + 1);
            //******* 更新账户表 ********
            flag = xnbiService.update(xbi, new EntityWrapper<Xnbi>().eq("uid", uid).eq("version", version));
            logger.debug(">>>xnbiService.update flag=" + flag);
        }
    }

    //积分及时入账
    private void addJifenFlow(User user, BigDecimal money, Boolean ruzhang, Integer fantimeType,
                              String sn, IotypeEnum iotype, JftypeEnum jftype, String remark) {
        Long uid = user.getId();
        Long mid = user.getMid();
        Long mpid = user.getMpid();

        JifenFlow jf = new JifenFlow();
        //*******  客户消耗  *******
        jf.setNum(money);
        jf.setSn(sn);//抵扣积分时 = 订单号
        jf.setIotype(iotype.getVal());//积分消费
        jf.setJftype(jftype.getVal());//积分消费
        jf.setFantimeType(fantimeType);
        jf.setCreatetime(new Date());
        jf.setUid(uid);
        jf.setMid(mid);
        jf.setMpid(mpid);
        jf.setRemark(jftype.getName());
        jf.setIsConfirm(1);
        jf.setConfirmDate(new Date());
        jf.setState(1);
        jf.insert();

        ruzhang = true;//积分及时入账,不在区分支付、核销、7天后入账

        Boolean flag = false;
        while (!flag) {
            Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", uid));
            if (jifen == null) jifen = jifenService.initJifen(uid, mid, mpid);

            long v = jifen.getVersion();
            BigDecimal total = iotype.getVal() == 1 ? jifen.getTotal().add(jf.getNum()) : jifen.getTotal().subtract(jf.getNum());
            BigDecimal fanliing = iotype.getVal() == 1 ? jifen.getFanliing().add(jf.getNum()) : jifen.getFanliing().subtract(jf.getNum());

            if (ruzhang) jifen.setTotal(total);
            else jifen.setFanliing(fanliing);

            jifen.setVersion(jifen.getVersion() + 1);
            jifen.setModifytime(new Date());
            jifen.setModifier(uid);

            flag = jifenService.update(jifen, new EntityWrapper<Jifen>().eq("version", v).eq("uid", uid));
            logger.debug(">>>at jifenService update=" + flag);
        }
    }

    private void fanliRuzhang(String sn, String fantimeType) {
        Order order = orderService.selectOne(new EntityWrapper<Order>().eq("order_no", sn));

        if (order == null) {
            logger.info("--------------------------------------fanliRuzhang order not exist for sn=" + sn);
            return;
        }
        if (order.getFantimeType() == null) {
            logger.info("--------------------------------------fanliRuzhang order.getFantimeType is null for fantimeType=" + fantimeType);
            return;
        }
        logger.info("--------------------------------------fanliRuzhang order=" + order);
        if (!order.getFantimeType().toString().equals(fantimeType)) {
            logger.info("--------------------------------------fanliRuzhang fantimeType not equal sn=" + sn);
            return;
        }

        Long uid = order.getUid();
        Long mid = order.getMid();
        Long mpid = order.getMpid();

        AccountFlow af = accountFlowService.selectOne(new EntityWrapper<AccountFlow>()
                .eq("sn", sn)
                .eq("xftype", XftypeEnum.xffanli.getVal())
        );
        Boolean flag = false;
        if (af != null) {
            uid = af.getUid();
            MerchantConfig mconfig = redisService.getMconfig(order.getMpid());
            User user = userService.selectById(uid);
            MerchantApp mapp = redisService.getMApp(mpid);
            boolean fanxian = mconfig.getIsAutofan() == 1;

            if (fanxian) {
                Map<String, Object> paymap = qnpay.payPakect(mpid, mapp.getAppid(), user, af.getRealpay(), "佣金奖励", "127.0.0.1");
                //如果秒退失败，该佣金自动到用户账户
                if (paymap.containsKey("result_code") && paymap.get("result_code").toString().equals("FAIL")) {
                    flag = false;
                } else if (paymap.containsKey("result_code") && paymap.get("result_code").toString().equals("SUCCESS")) {
                    //秒到账成功
                    addMaccountFlow(user, af.getAmount(), sn, IotypeEnum.output, XftypeEnum.xffanli, order.getTransactionId());

                    AccountFlow naf = new AccountFlow();
                    naf.setTotal(af.getAmount());
                    naf.setAmount(af.getAmount());
                    naf.setDikou(new BigDecimal(0));//总营销金额 130
                    naf.setRealpay(new BigDecimal(0));//总价200 实付100

                    naf.setNickname(user != null ? user.getNickName() : null);
                    naf.setHeadimg(user != null ? user.getAvatarPic() : null);
                    naf.setPhone(user != null ? user.getPhone() : null);

                    naf.setSn(sn);
                    naf.setTransactionid(paymap.get("payment_no").toString());
                    naf.setIotype(IotypeEnum.output.getVal());//个人账户出账
                    naf.setXftype(XftypeEnum.withdraw.getVal());//个人消费
                    naf.setFantimeType(af.getFantimeType());

                    naf.setIsConfirm(-1);
                    naf.setState(1);
                    naf.setTradetime(new Date());
                    naf.setCreatetime(af.getTradetime());
                    naf.setRemark("佣金提现至微信账户【" + sn + "】");
                    naf.setUid(uid);
                    naf.setMid(mid);
                    naf.setMpid(mpid);
                    naf.insert();

                    Account naccount = new Account();
                    while (!flag) {
                        Account account = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
                        if (account == null) {
                            account = accountService.initAccount(uid, mid, mpid);
                        }

                        naf.setIsConfirm(1);
                        naf.setRuzhang(1);
                        naf.setLasttotal(account.getTotal());
                        naf.setConfirmDate(new Date());

                        Long version = account.getVersion();

                        BigDecimal total = account.getTotal();
                        BigDecimal fanliing = account.getFanliing();

                        naccount.setTotal(total.subtract(af.getAmount()));
                        naccount.setFanliing(fanliing.subtract(af.getAmount()));

                        naccount.setModifytime(new Date());
                        naccount.setModifier(uid);
                        naccount.setVersion(version + 1);

                        flag = accountService.update(naccount, new EntityWrapper<Account>().eq("uid", uid).eq("version", version));
                        if (flag) naf.updateById();
                    }
                }
            }
            //如果失败，直接转至余额账户
            Account naccount = new Account();
            while (!flag) {
                Account account = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
                if (account == null) {
                    break;
                }
                Long version = account.getVersion();

                BigDecimal amount = account.getAmount();
                BigDecimal fanliing = account.getFanliing();

                naccount.setAmount(amount.add(af.getAmount()));
                naccount.setFanliing(fanliing.subtract(af.getAmount()));

                naccount.setModifytime(new Date());
                naccount.setModifier(uid);
                naccount.setVersion(version + 1);

                flag = accountService.update(naccount, new EntityWrapper<Account>().eq("uid", uid).eq("version", version));
            }
        }

        JifenFlow jf = jifenFlowService.selectOne(new EntityWrapper<JifenFlow>()
                .eq("sn", sn)
                .eq("fantime_type", fantimeType)
                .eq("jftype", XftypeEnum.xffanli.getVal())
        );

        flag = false;
        while (!flag && jf != null) {
            uid = jf.getUid();

            Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", uid));
            if (jifen == null) {
                break;
            }
            Long version = jifen.getVersion();

            jifen.setTotal(jifen.getTotal().add(jf.getNum()));
            jifen.setFanliing(jifen.getFanliing().subtract(jf.getNum()));

            jifen.setModifytime(new Date());
            jifen.setModifier(uid);
            jifen.setVersion(version + 1);

            flag = jifenService.update(jifen, new EntityWrapper<Jifen>().eq("uid", uid).eq("version", version));
        }

        XnbiFlow xf = xnbiFlowService.selectOne(new EntityWrapper<XnbiFlow>()
                .eq("sn", sn)
                .eq("fantime_type", fantimeType)
                .eq("jftype", XftypeEnum.xffanli.getVal())
        );

        flag = false;
        while (!flag && xf != null) {
            uid = xf.getUid();

            Xnbi xbi = xnbiService.selectOne(new EntityWrapper<Xnbi>().eq("uid", uid));
            if (xbi == null) {
                break;
            }
            Long version = xbi.getVersion();

            xbi.setTotal(xbi.getTotal().add(xf.getNum()));
            xbi.setFanliing(xbi.getFanliing().subtract(xf.getNum()));

            xbi.setModifytime(new Date());
            xbi.setModifier(uid);
            xbi.setVersion(version + 1);

            flag = xnbiService.update(xbi, new EntityWrapper<Xnbi>().eq("uid", uid).eq("version", version));
        }
    }

    private void paidanRuzhang(String sn, String fantimeType) {
        Order order = orderService.selectOne(new EntityWrapper<Order>().eq("order_no", sn));

        if (order == null) {
            logger.info("--------------------------------------fanliRuzhang order not exist for sn=" + sn);
            return;
        }
        if (order.getFantimeType() == null) {
            logger.info("--------------------------------------fanliRuzhang order.getFantimeType is null for fantimeType=" + fantimeType);
            return;
        }
        logger.info("--------------------------------------fanliRuzhang order=" + order);
        if (!order.getFantimeType().toString().equals(fantimeType)) {
            logger.info("--------------------------------------fanliRuzhang fantimeType not equal sn=" + sn);
            return;
        }

        Long uid = order.getJduid();
        User user = userService.selectById(uid);
        Boolean ruzhang = false;

        addAccountFlow(user, order.getMinprice(), ruzhang, order.getFantimeType(), order, IotypeEnum.input, XftypeEnum.jiedanyongji);
    }

    private void pintuanUpdate(Order order) {
        logger.info("---------------------orderActor pintuanUpdate coming at order=" + JSON.toJSONString(order));
        PintuanLog pintuanLog = pintuanLogService.selectOne(new EntityWrapper<PintuanLog>()
                .eq("oid", order.getId())
                .eq("uid", order.getUid()));
        if (pintuanLog == null) {
            logger.info("---------------------orderActor pintuanUpdate fail for pintuanLog null at order=" + JSON.toJSONString(order));
            return;
        }

        PintuanLog npintuanLog = new PintuanLog();
        npintuanLog.setId(pintuanLog.getId());
        npintuanLog.setState(1);
        npintuanLog.updateById();

        PintuanOpen pintuanOpen = pintuanOpenService.selectOne(new EntityWrapper<PintuanOpen>()
                .setSqlSelect("id,status,ptotal,pnumber")
                .eq("id", pintuanLog.getPtoid()));
        if (pintuanOpen == null) {
            logger.info("pintuanOpen not found for oid=" + order.getId());
            return;
        }
        pintuanOpen.setPnumber(pintuanOpen.getPnumber() + 1);
        if (pintuanOpen.getPtotal() - pintuanOpen.getPnumber() == 0) {
            pintuanOpen.setStatus(PTstatus.ok.getVal());

            List<PintuanLog> pintuanLogs = pintuanLogService.selectList(new EntityWrapper<PintuanLog>()
                    .eq("ptoid", pintuanOpen.getId()));
            //更新订单状态
            for (PintuanLog item : pintuanLogs) {
                Order norder = new Order();
                norder.setId(item.getOid());
                norder.setStatus(StatusEnum.receving.getVal());
                norder.updateById();
            }
        }

        pintuanOpen.setState(1);
        pintuanOpen.updateById();
    }

    private void kanjiaUpdate(Order order) {

        CutpriceOpen cutpriceOpen = cutpriceOpenService.selectOne(new EntityWrapper<CutpriceOpen>()
                .eq("oid", order.getId()));
        if (cutpriceOpen != null) {
            CutpriceOpen ncutpriceOpen = new CutpriceOpen();
            ncutpriceOpen.setId(cutpriceOpen.getId());
            ncutpriceOpen.setEndtime(new Date());
            ncutpriceOpen.setStatus(PTstatus.ok.getVal());
            ncutpriceOpen.setModifier(order.getUid());
            ncutpriceOpen.setModifytime(new Date());
            ncutpriceOpen.updateById();
        }
    }

    private void goodsAndOrderUpdate(Order order) {

        Goods goods = goodsService.selectById(order.getGid());
        logger.info("---------------------goodsAndOrderUpdate goods=" + JSON.toJSONString(goods));
        if (goods == null || (order.getXftype() == null && order.getXftype().intValue() == XftypeEnum.paidan.getVal()))
            return;

        Goods ngoods = new Goods();
        ngoods.setId(order.getGid());
        ngoods.setCanyushu(goods.getCanyushu() == null ? 1 : goods.getCanyushu() + 1);

        ngoods.setNumberOrders(goods.getNumberOrders() + 1);
        if (order.getType().intValue() == YXType.choujiang.getVal()) {

        } else if (order.getType().intValue() == YXType.toupiao.getVal() || order.getType().intValue() == YXType.jizan.getVal()) {
            ngoods.setNumberSale(goods.getNumberSale() == null ? 1 : goods.getNumberSale() + 1);
        } else {
            ngoods.setNumberSale(goods.getNumberSale() == null ? order.getGoodsNumber() : goods.getNumberSale() + order.getGoodsNumber());
        }

        if (goods.getType() == YXType.choujiang.getVal()) {
            //抽奖模式，不减少库存

        } else {
            if (goods.getStores() != null && goods.getStores().intValue() > 0) {
                ngoods.setStores(goods.getStores() - order.getGoodsNumber());
                goods.setStores(goods.getStores() - order.getGoodsNumber());
            }
            if (goods.getStores() != null & goods.getStores().intValue() <= 0) {
                ngoods.setStatus(Gstatus.over.getVal());

                //砍价结束
                if (goods.getType() == YXType.kanjia.getVal()) {
                    //更新所有未成交订单为活动失败状态
                    Order unorder = new Order();
                    unorder.setGid(goods.getId());
                    unorder.setStatus(StatusEnum.cancel.getVal());
                    unorder.setRemark("该活动商品已售罄，订单自动取消，欢迎下次再参与");
                    unorder.setModifytime(new Date());
                    orderService.update(unorder, new EntityWrapper<Order>()
                            .eq("status", 1).eq("gid", goods.getId()));

                    //更新订单商品
                    OrderGoods unorderGoods = new OrderGoods();
                    unorderGoods.setGid(goods.getId());
                    unorderGoods.setStatus(StatusEnum.cancel.getVal());
                    unorderGoods.setModifytime(new Date());

                    orderGoodsService.update(unorderGoods, new EntityWrapper<OrderGoods>()
                            .eq("status", 1).eq("gid", goods.getId()));

                    //更新砍价订单(正在进行的砍价活动)
                    CutpriceOpen cutpriceOpen = new CutpriceOpen();
                    cutpriceOpen.setStatus(0);
                    cutpriceOpen.setModifytime(new Date());
                    cutpriceOpenService.update(cutpriceOpen, new EntityWrapper<CutpriceOpen>()
                            .eq("status", 1).eq("gid", goods.getId()));
                }
            }
        }

        ngoods.setModifytime(new Date());
        ngoods.setModifier(order.getUid());
        logger.info("---------------------orderActor pintuanUpdate ngoods=" + JSON.toJSONString(ngoods));
        ngoods.updateById();

        //订单状态更新
        Order norder = new Order();
        norder.setId(order.getId());
        norder.setState(1);
        if (order.getType().intValue() == YXType.pintuan.getVal()
                || order.getType().intValue() == YXType.choujiang.getVal()
                || order.getType().intValue() == YXType.toupiao.getVal())
            //拼团|抽奖|投票
            norder.setStatus(StatusEnum.forsend.getVal());
        else if (order.getType().intValue() == YXType.dalibao.getVal()) {
            norder.setStatus(StatusEnum.finish.getVal());
        }
        logger.info("--------------------------------------------------22----norder.getStatus()=" + norder.getStatus());
        norder.updateById();
    }

    //体验卡
    private void tiyanka(Goods goods, Order order) {

        logger.info("--------------------------------------------------start to tiyanka");
        CouponTpl ctpl = couponTplService.selectById(goods.getTplid());
        logger.info("--------------------------------------couponTpl=" + JSON.toJSONString(ctpl));

        if (ctpl == null) return;

        Coupon coupon = new Coupon();
        coupon.setIsUnused(1);//未使用
        coupon.setIsUsed(0);//已使用
        coupon.setIsForever(ctpl.getIsForever());//永久有效
        coupon.setIsOutdate(0);//已过期
        coupon.setState(1);

        coupon.setMid(order.getMid());
        coupon.setMpid(order.getMpid());
        coupon.setUid(order.getUid());
        coupon.setSid(ctpl.getSid());
        Store store = redisService.getStore(ctpl.getSid());
        if (store != null) {
            coupon.setAddress(store.getAddress());
        }
        coupon.setCreatetime(new Date());

        coupon.setTplid(ctpl.getId());
        coupon.setType(ctpl.getType());
        coupon.setName(ctpl.getName());
        coupon.setSlogo(ctpl.getSlogo());
        coupon.setSname(ctpl.getSname());
        coupon.setRemark(ctpl.getRemark());
        if (ctpl.getType() == 10 && ctpl.getDiscount() != null) {
            coupon.setUsemin(ctpl.getDiscount());
            coupon.setXmtype(ctpl.getXmtype());
        }

        coupon.setUsemin(new BigDecimal(0));
        coupon.setPic(ctpl.getPic());
        coupon.setOid(order.getId());

        coupon.setCno(StringUtil.getQuanCode(order.getMid()));
        coupon.setSn(order.getOrderNo());

        coupon.setStarttime(DateUtil.getToday());
        coupon.setEndtime(ctpl.getType().intValue() == 10 ? DateUtil.addToday(365) :
                ctpl.getType().intValue() == 11 ? DateUtil.addToday(7) :
                        ctpl.getType().intValue() == 12 ? DateUtil.addToday(30) :
                                ctpl.getType().intValue() == 13 ? DateUtil.addToday(90) :
                                        ctpl.getType().intValue() == 14 ? DateUtil.addToday(180) :
                                                ctpl.getType().intValue() == 15 ? DateUtil.addToday(365) :
                                                        ctpl.getType().intValue() == 16 ? DateUtil.addToday(3650) : "");

        coupon.setCost(ctpl.getCost());
        coupon.setUsemin(ctpl.getUsemin() == null ? new BigDecimal(0) : ctpl.getUsemin());
        coupon.setOriginType(Qgettype.chongzhi.getVal());//领券来源@1：领取；2：分享；3：赠送;4：充值&

        coupon.insert();

        //领取+1
        CouponTpl ctpl2 = new CouponTpl();
        ctpl2.setId(ctpl.getId());
        ctpl2.setUse(ctpl.getUse() + 1);
        ctpl2.setModifytime(new Date());
        ctpl2.setModifier(ctpl.getUid());
        ctpl2.updateById();
    }

    //处理订单fanuid
//    private void orderFanuid(Order order) {
//
//        logger.debug("-------------------------------------------------start to orderFanuid oid=" + order.getId());
//
//        Long fanuid = null;
//        String[] oris = order.getOri().split("@");
//        if (oris.length >= 1) {
//            String scene = oris[0];
//            if (Strings.isNullOrEmpty(scene) || scene.equals("null")) return;
//            // scene format //uid+page+act+ywid
//            //uid.toString() + "_jfzhifu_Q_" + ywid;
//            try {
//                fanuid = Long.parseLong(scene.split("_")[0]);
//            } catch (Exception e) {
//                logger.error("orderFanuid Long.parseLong fanuid error", e);
//                return;
//            }
//        }
//
//        if (oris.length >= 2) {
////            9c7d2de6-d921-3cfd-f14d-3fcd89f270d8_miaosha_button_31005
//            String ori = oris[1];
//            String guid = ori.split("_")[0];
//            User user = userService.selectOne(new EntityWrapper<User>().setSqlSelect("id,guid").eq("guid", guid));
//            if (user != null) fanuid = user.getId();
//        }
//
//        if (fanuid != null) {
//            order.setFanuid(fanuid);
//            Order norder = new Order();
//            norder.setFanuid(fanuid);
//            norder.setId(order.getId());
//            norder.updateById();
//            logger.debug("--------------------------------------------orderFanuid ok");
//        }
//    }

    //优惠买单推荐奖励
    public void shymaidanOrder(Order order) {
        String tradeCode = order.getTradecode();
        User user = userService.selectById(order.getUid());
        logger.info("--------------------------------------shymaidanOrder tradeCode=" + tradeCode);
        logger.info("--------------------------------------shymaidanOrder order.getXftype().intValue()=" + order.getXftype().intValue());
        try {
            if (order.getXftype().intValue() == XftypeEnum.shymaidan.getVal() && !Strings.isNullOrEmpty(tradeCode)) {
                logger.info("--------------------------------------XftypeEnum.shymaidan.getVal()");
                String[] codes = tradeCode.split("_");
                String type = codes[0];//类型
                int level = Integer.valueOf(codes[1]);//级别
                int expire = Integer.valueOf(codes[2]);//期限

                if (!Strings.isNullOrEmpty(type) && type.equals("agent")) {
                    //升级用户+盟主信息
                    User nuser = new User();
                    nuser.setId(user.getId());
                    nuser.setAlevel(level);
                    nuser.setIsAdmin(1);
                    nuser.setIsAgent(1);

                    Date enddate = user.getEndtime();
                    if (enddate == null) {
                        nuser.setStarttime(new Date());
                        nuser.setEndtime(DateUtil.addDay(nuser.getStarttime(), expire * 30));
                    } else {
                        nuser.setStarttime(user.getStarttime());
                        nuser.setEndtime(DateUtil.addDay(enddate, expire * 30));
                    }
                    nuser.setModifytime(new Date());

                    League entity = new League();
                    entity.setUid(user.getId());
                    League league = leagueMapper.selectOne(entity);
                    if (league == null) {
                        league = entity;
                        league.setStarttime(nuser.getStarttime());
                        league.setEndtime(nuser.getEndtime());

                        league.setUid(user.getId());
                        league.setMid(user.getMid());
                        league.setLinkman(user.getNickName());
                        league.setPhone(user.getPhone());
                        league.setWxno(user.getWeixin());
                        league.setCreatetime(new Date());
                    } else {
                        league.setModifytime(new Date());
                    }

                    league.setState(1);
                    league.setStatus(2);
                    league.insertOrUpdate();

                    //更新用户信息
                    nuser.setLeagueid(league.getId());
                    nuser.updateById();
                    redisService.delUser(user.getId());

                } else if (!Strings.isNullOrEmpty(type) && type.equals("mch")) {
                    //升级商家User+Store
                    Long sid = user.getSid();
                    Store store = storeService.selectOne(new EntityWrapper<Store>().eq("uid", user.getId()));
                    Store nstore = new Store();
                    if (store != null) nstore.setId(sid);

                    User nuser = new User();
                    nuser.setId(user.getId());
                    nuser.setSlevel(level);
                    nuser.setIsAdmin(1);
                    nuser.setIsMch(1);

                    Date enddate = user.getEndtime();
                    if (enddate == null) {
                        nuser.setStarttime(new Date());
                        nuser.setEndtime(DateUtil.addDay(nuser.getStarttime(), expire * 30));

                        if (store != null) {
                            nstore.setStarttime(nuser.getStarttime());
                            nstore.setEndtime(nuser.getEndtime());
                            nstore.setMlevel(level);
                        }
                    } else {
                        nuser.setEndtime(DateUtil.addDay(enddate, expire * 30));
                        if (store != null) {
                            nstore.setEndtime(nuser.getEndtime());
                            nstore.setMlevel(level);
                        }
                    }
                    nuser.setModifytime(new Date());
                    //更新用户信息
                    nuser.updateById();
                    redisService.delUser(user.getId());

                    //更新商家信息
                    if (store != null) {
                        nstore.setState(1);
                        nstore.setStatus(2);
                        nstore.setIsAuth(1);
                        nstore.setModifytime(new Date());
                        nstore.updateById();
                    }
                } else if (!Strings.isNullOrEmpty(type) && type.equals("member")) {

                }
            }
        } catch (Exception e) {
            logger.error("--------------------------------------shymaidanOrder error", e);
        }
    }

    //优惠买单推荐奖励
    public void insertMchmembers(Order order) {
        if (order.getSid() == null) {
            logger.info("------------------------insertMchmembers order.getSid()=" + order.getSid());
            return;
        }

        User user = userService.selectById(order.getUid());
        logger.info("--------------------------------------insertMchmembers user=" + JSON.toJSONString(user));
        LeagueMember entity = new LeagueMember();
        entity.setSid(order.getSid());
        entity.setUid(order.getUid());
        LeagueMember leagueMember = leagueMemberMapper.selectOne(entity);
        //更新为客户
        if (leagueMember == null) {
            leagueMember = entity;
            leagueMember.setMid(order.getMid());
            leagueMember.setMpid(order.getMpid());
            leagueMember.setCreatetime(new Date());
            leagueMember.setPhone(user.getPhone() == null ? order.getPhone() : user.getPhone());
            leagueMember.setNickname(order.getLinkman());
            leagueMember.setHeadimg(order.getHeadimg() == null ? redisService.getUser(order.getUid()).getAvatarPic() : order.getHeadimg());
            leagueMember.setLeagueid(order.getLeagueid());
            leagueMember.setCreateday(DateUtil.getToday());
            leagueMember.setState(1);
            leagueMember.setUtype(Utype.kehu.getVal());
            leagueMember.setMlevel(-1);
            leagueMember.setSname(redisService.getStore(order.getSid()).getName());
            leagueMember.setLastxf(DateUtil.getToday());

            if (!Strings.isNullOrEmpty(order.getOri()))
                leagueMember.setShareid(ObjectUtil.orderFanuid(order.getOri()));
            if (leagueMember.getShareid() != null) {
                User shareuser = userService.selectOne(new EntityWrapper<User>().setSqlSelect("id,nick_name nickName")
                        .eq("id", leagueMember.getShareid()));
                leagueMember.setSharename(shareuser == null ? null : shareuser.getNickName());
            }
//            leagueMember.insert();
        } else if (leagueMember.getUtype().intValue() < Utype.kehu.getVal()) {
            leagueMember.setUtype(Utype.kehu.getVal());
        }
        leagueMember.insertOrUpdate();
    }

    //平台优惠券买单分佣
    //===待完善
    public void shareSmaidanFan(Order order) {

        logger.info("----------------------------shareFan come");

        //返现用户
        Long mpid = order.getMpid();
        Long fanuid = order.getFanuid();
        logger.debug("---------------------------shareSmaidanFan for fanuid=" + fanuid);
        logger.debug("---------------------------shareSmaidanFan for order.getSharefan()=" + order.getSharefan());
        if (order.getSharefan() == null || order.getSharefan().doubleValue() <= 0) {
            return;
        }

        if (fanuid == null) {
            return;
        }

        //秒到+非秒到账
        BigDecimal fxe = order.getSharefan();
        User fxuser = userService.selectById(fanuid);
        MerchantConfig mconfig = redisService.getMconfig(mpid);

        //mconfig.getIsMiaotui() 该属性针对现金返佣来说
        //mconfig.getIsAutofan() 该属性针对现金返佣来说
        //直接入账触发点 1：支付成功后；2：确认收货|扫码核销后；3：确认后7天到账&
        //==待实现 3：确认后7天到账&
        //否则先放入待返利中。。。
        boolean ruzhang = true;
        boolean nowfan = mconfig.getIsAutofan() == 1 && ruzhang;
        logger.info("------------------------------------------------------shareSmaidanFan autofan=" + nowfan);

        fanyong(fxuser, fxe, XffanType.qian.getVal(), FantimeType.payok.getVal(), order, ruzhang, nowfan, XftypeEnum.sharefan);

        logger.info("-----------------------------------shareSmaidanFan over");
    }

    //处理订单fanuid
    //普通推荐有礼触发+
    //触发裂变红包奖励
    private void quanSharepay(String zfuid, String tplid, String quanid, String fantimetype) {

        logger.debug("-------------------------------------------------start to quanSharepay zfuid=" + zfuid);
        logger.debug("-------------------------------------------------start to quanSharepay tplid=" + tplid);

        CouponTpl ctpl = couponTplService.selectById(tplid);
        Coupon coupon = couponService.selectById(quanid);
        if (ctpl == null) {
            logger.debug("-----------------quanSharepay ctpl=null at tplid=" + tplid);
            return;
        }
        logger.debug("-----------------quanSharepay ctpl=" + JSON.toJSONString(ctpl));
        if (ctpl.getFenxiao().intValue() == Qfxtype.none.getVal() || ctpl.getFenxiao().intValue() == Qfxtype.fenxiao.getVal()
                || ctpl.getFantype() == null || ctpl.getFantype() == 0) {
            return;
        }
        if (ctpl.getFxshu() > 0 && ctpl.getFanshu() != null
                && ctpl.getFanshu() >= ctpl.getFxshu()) {
            return;
        }


        String sn = coupon.getCno();
        Order order = new Order();
        order.setOrderNo(sn);
        User user = userService.selectById(zfuid);
        BigDecimal fxe = ctpl.getFanmount();
        Long ftplid = ctpl.getFanid();
        Long uid = Long.parseLong(zfuid);
        boolean fflag = false;

        Saccount saccount = saccountService.selectById(ctpl.getSid());
        if (saccount.getAmount().doubleValue() < fxe.doubleValue()) {
            logger.error("-----------------no amount money left for quanSharepay for sid=" + ctpl.getSid());
            return;
        }

        if (ctpl.getFantype().intValue() == XffanType.jifen.getVal()) {
            jffanyong(user, fxe, XffanType.jifen.getVal(), sn, true, JftypeEnum.share);
            fflag = true;
        } else if (ctpl.getFantype() == XffanType.qian.getVal()) {
            //计算佣金随机
//            BigDecimal money = RandSplitNumUtils.genRandPack(fxe.intValue());
            BigDecimal money = fxe;

            SaccountFlow saccountFlow = new SaccountFlow();
            saccountFlow.setIotype(-1);
            saccountFlow.setRuzhang(0);
            saccountFlow.setTotal(fxe);
            saccountFlow.setAmount(new BigDecimal(0));
            saccountFlow.setMamount(fxe);
            saccountFlow.setYouhui(new BigDecimal(0));

            saccountFlow.setTradetime(new Date());
            saccountFlow.setSn(sn);
            saccountFlow.setState(1);
            saccountFlow.setType(1);
            saccountFlow.setXftype(XftypeEnum.autofanli.getVal());
            saccountFlow.setXftypename(XftypeEnum.autofanli.getName());

            saccountFlow.setMid(ctpl.getMid());
            saccountFlow.setMpid(ctpl.getMpid());
            saccountFlow.setSid(ctpl.getSid());
            saccountFlow.setLeagueid(ctpl.getLeagueid());

            mchfanyong(user, money, XffanType.qian.getVal(), Integer.parseInt(fantimetype), order, true, true, XftypeEnum.autofanli, saccountFlow);
            fflag = true;
        } else if (ctpl.getFantype() == XffanType.quan.getVal()) {
            CouponTpl nctpl = couponTplService.selectById(ftplid);
            if (nctpl == null) return;
            couponService.lingQuan("", null, uid, nctpl, Qgettype.jiangli);
            fflag = true;
        } else if (ctpl.getFantype() == XffanType.xnbi.getVal()) {
            fanyong(user, fxe, XffanType.xnbi.getVal(), Integer.parseInt(fantimetype), order, true, true, XftypeEnum.autofanli);
            fflag = true;
        }

        if (fflag) {
            CouponTpl ncouponTpl = new CouponTpl();
            ncouponTpl.setId(ctpl.getId());
            ncouponTpl.setFanshu(ctpl.getFanshu() == null ? 1 : ctpl.getFanshu() + 1);
            ncouponTpl.setModifytime(new Date());
            ncouponTpl.updateById();
        }

    }

    //处理购买会员返订单
    private void buyHuiyuanFan(Order order) {

        logger.debug("-------------------------------------------------start to buyHuiyuanFan order=" + order);
        Czfan czfan = czfanService.selectById(order.getTradecode());
        if (czfan == null || czfan.getFanquan() == null) return;

        logger.debug("--------------------------------------czfan =" + czfan);
        //处理充值返券，券再支付成功确认后，才分配到用户账户
        if (czfan != null && czfan.getFanquan() != null && czfan.getFanquan() > 0 && czfan.getQuanshu() > 0) {
            CouponTpl ctpl = couponTplService.selectById(czfan.getFanquan());
            logger.debug("--------------------------------------ctpl =" + ctpl);

            for (int i = 0; i < czfan.getQuanshu(); i++) {
                if (ctpl == null) {
                    logger.error("======couponTpl is null for id=" + czfan.getFanquan());
                    break;
                }
                Coupon coupon = new Coupon();
                coupon.setIsUnused(1);//未使用
                coupon.setIsUsed(0);//已使用
                coupon.setIsForever(ctpl.getIsForever());//永久有效
                coupon.setIsOutdate(0);//已过期
                coupon.setState(1);

                coupon.setMid(order.getMid());
                coupon.setMpid(order.getMpid());
                coupon.setUid(order.getUid());
                coupon.setSid(ctpl.getSid());
                coupon.setCreatetime(new Date());

                coupon.setTplid(ctpl.getId());
                coupon.setType(ctpl.getType());
                coupon.setName(ctpl.getName());
                coupon.setSlogo(ctpl.getSlogo());
                coupon.setSname(ctpl.getSname());
                coupon.setRemark(ctpl.getRemark());

                coupon.setCno(StringUtil.getQuanCode(order.getMid()));
                coupon.setSn(order.getOrderNo());

                coupon.setStarttime(ctpl.getValidType() == 1 ? DateUtil.getToday() : ctpl.getStarttime());
                coupon.setEndtime(ctpl.getIsForever() == 1 ? null : ctpl.getValidType() == 1 ? DateUtil.addToday(ctpl.getExpire()) : ctpl.getEndtime());
                coupon.setCost(ctpl.getCost());
                coupon.setUsemin(ctpl.getUsemin());
                coupon.setOriginType(Qgettype.chongzhi.getVal());//领券来源@1：领取；2：分享；3：赠送;4：充值&

                coupon.insert();
            }
            logger.debug("--------------------------------------czfan.getQuanshu() =" + czfan.getQuanshu());

            //更新模板状态
            if (ctpl != null) {
                ctpl.setUse(ctpl.getUse() + czfan.getQuanshu());
                ctpl.updateById();
            }
            //更新订单状态
            Order norder = new Order();
            norder.setId(order.getId());
            norder.setStatus(StatusEnum.finish.getVal());
            norder.setModifytime(new Date());
            norder.updateById();

            //更新会员等级
            User nuser = new User();
            nuser.setId(order.getUid());
            nuser.setIsMember(1);
            nuser.setMemberLevel(czfan.getLevel());

            nuser.setStarttime(new Date());
            nuser.setEndtime(DateUtil.addDay(nuser.getStarttime(), czfan.getExpire() == null ? 365 : czfan.getExpire()));
            nuser.setModifytime(new Date());
            nuser.updateById();

            redisService.delUser(order.getUid());
            User user = userService.selectOne(new EntityWrapper<User>().setSqlSelect("id,guid")
                    .eq("id", order.getUid()));
            redisService.delUserByguid(user.getGuid());
        }
    }

    //套餐活动关联产品自动购买
    private void autoOrder(Goods goods, Order order) {
        Long oid = order.getId();
        order.setId(null);
        Long gid = goods.getLogisticsId();
        Goods glgoods = goodsService.selectById(gid);
        if (glgoods == null) return;

        order.setGid(gid);
        order.setOrderNo(order.getOrderNo() + "1");
        order.setShipperMethod(Pstype.kuaidi.getVal());

        Address addr = addressService.selectById(order.getAddrid());
        order.setAddress(addr.getCity() == "市辖区" ? addr.getProvince() + addr.getDistrict() + addr.getAddress() : addr.getProvince() + addr.getCity() + addr.getDistrict() + addr.getAddress());

        order.setLinkman(addr.getLinkman());
        order.setPhone(addr.getPhone());
        order.setPrepayid(null);

        order.setPic(glgoods.getPic());
        order.setGoodsName(glgoods.getName());
        order.setPrice(glgoods.getPrice());
        order.setSaleprice(glgoods.getSaleprice());
        order.setRealpay(new BigDecimal(0));
        order.setTotal(glgoods.getSaleprice());
        order.setGtype(glgoods.getGtype());
        if(glgoods.getGtype().intValue()==GtypeEnum.real.getVal()){
            order.setStatus(StatusEnum.forsend.getVal());
        }else if(glgoods.getGtype()==GtypeEnum.xu.getVal()){
            order.setStatus(StatusEnum.receving.getVal());
        }
        order.setFantimeType(FantimeType.not.getVal());
        order.setFanuid(null);
        order.setSharefan(null);

        order.setSid(3766l);
        order.setSname("华口商城");
        order.insert();

        OrderGoods og = orderGoodsService.selectOne(new EntityWrapper<OrderGoods>().eq("oid", oid));
        if (og == null) og = new OrderGoods();

        og.setId(null);
        og.setOid(order.getId());
        og.setOrderNo(order.getOrderNo());

        og.setPic(glgoods.getPic());
        og.setGoodsName(glgoods.getName());
        og.setPrice(glgoods.getPrice());
        og.setSaleprice(glgoods.getSaleprice());
        og.setTotal(glgoods.getSaleprice());
        og.setRealpay(order.getRealpay());
        og.setGtype(glgoods.getGtype());
        og.setStatus(order.getStatus());
        og.setState(1);
        og.setFhstate(1);
        og.setSharefan(null);
        og.setType(glgoods.getType());
        og.setIsDeleted(-1);
        og.setOrderType(0);

        og.setIsComment(-1);
        og.setIsDeleted(1);
        og.setHeadimg(redisService.getUser(order.getUid()).getAvatarPic());
        og.setNumber(1);
        BigDecimal zero = new BigDecimal(0);
        og.setDiscount(zero);
        og.setJifen(0);

        og.setSid(3766l);
        og.setSname("华口商城");

        og.setPhone(order.getPhone());
        og.setLinkman(order.getLinkman());

        og.setMid(order.getMid());
        og.setMpid(order.getMpid());
        og.setUid(order.getUid());
        og.setPaytime(order.getPaytime());
        og.setCreatetime(new Date());

        og.insert();

    }


}
